美文网首页
iOS技术文档No.23 Foundation_NSOperat

iOS技术文档No.23 Foundation_NSOperat

作者: 孤独雪域 | 来源:发表于2017-07-25 12:00 被阅读30次

    本篇文章主要介绍下多线程下NSOperation、NSBlockOperation、NSInvocationOperation、NSOperationQueue的使用,列举几个简单的例子。

    默认情况下,NSOperation并不具备封装操作的能力,必须使用它的子类,使用NSOperation子类的方式有3种:

    1> 自定义子类继承NSOperation,实现内部相应的方法
    2> NSBlockOperation
    3>NSInvocationOperation
    这讲先介绍如何用NSOperation封装一个操作,后面再结合NSOperationQueue来使用。
    1.首先介绍自定义NSOperation:NSOperation是没法直接使用的,它只是提供了一个工作的基本逻辑,具体实现还是需要你通过定义自己的NSOperation子类来获得。

    #import <Foundation/Foundation.h>  
      
    @protocol NSDefineOprationDelegate <NSObject>  
      
    - (void) handleDelegate;  
      
    @end  
      
    @interface NSDefineOpration : NSOperation  
      
    @property (nonatomic, assign) id <NSDefineOprationDelegate> delegate;  
      
    - (id)initWithDelegate:(id<NSDefineOprationDelegate>) delegate;  
    @end  
    

    实现文件里:

    #import "NSDefineOpration.h"  
      
    @implementation NSDefineOpration  
      
    - (id)initWithDelegate:(id<NSDefineOprationDelegate>) delegate  
    {  
        if(self = [super init])  
        {  
            self.delegate = delegate;  
        }  
        return self;  
    }  
      
    - (void)main  
    {  
        @autoreleasepool {  
            //do something  
            sleep(15);  
            NSLog(@"op1........handle......  on thread num :%@",[NSThread currentThread]);  
              
            if([self.delegate respondsToSelector:@selector(handleDelegate)])  
            {  
                [self.delegate performSelector:@selector(handleDelegate) withObject:nil];  
            }  
        }  
          
    }  
      
    @end  
    

    这里的sleep(15)主要用来做一些延时的操作,比如网络下载等。调用:

    
    - (void)oprationTest  
    {  
        NSDefineOpration *op1 = [[NSDefineOpration alloc] initWithDelegate:self];  
        op1.completionBlock = ^(){  
            NSLog(@"op1........OK !!");  
        };  
        [op1 start];  
    }  
    

    执行结果:

    2017-07-25 12:07:01.051 No.22 Foundation_NSOperation[20340:1394940] op1........handle......  on thread num :<NSThread: 0x600000067c80>{number = 1, name = main}
    2017-07-25 12:07:01.052 No.22 Foundation_NSOperation[20340:1395366] op1........OK !!
    
    

    从执行结果可以看出,因为在实现的main函数里没有使用异步线程处理,导致直接阻塞了主线程1,所以使用这种方式一定注意main函数里操作时间过长导致主线程阻塞问题。耗时比较长的都放到其他线程里处理。

    2.接下来介绍NSBlockOperation
    第一种使用NSBlockOperation的方式:

    
    NSLog(@"block start");  
    NSBlockOperation *bop2 = [NSBlockOperation blockOperationWithBlock:^{  
        sleep(15);  
        NSLog(@"bop2.....handle..... on thread num%@",[NSThread currentThread]);  
    }];  
    [bop2 setCompletionBlock:^{  
        NSLog(@"bop2........OK !!");  
    }];  
    [bop2 start];  
    
    • 第2行初始化了一个NSBlockOperation对象,它是用一个Block来封装需要执行的操作
    • 第9行调用了start方法,紧接着会马上执行Block中的内容
      看下执行结果:
    2017-07-25 13:48:15.948 No.22 Foundation_NSOperation[20717:1441242] block start
    2017-07-25 13:48:30.950 No.22 Foundation_NSOperation[20717:1441242] bop2.....handle..... on thread num<NSThread: 0x608000062780>{number = 1, name = main}
    2017-07-25 13:48:30.951 No.22 Foundation_NSOperation[20717:1441598] bop2........OK !!
    
    • 这里还是在当前线程同步执行操作,并没有异步执行,阻塞主线程。
      第二种使用NSBlockOperation的方式:
    - (void)blockOprationTest  
    {  
        NSLog(@"block start");  
        NSBlockOperation * op2 = [[NSBlockOperation alloc] init];  
        [op2 addExecutionBlock:^{  
            sleep(10);  
            NSLog(@"op2.....handle..... on 10 hread num%@",[NSThread currentThread]);  
        }];  
          
        [op2 addExecutionBlock:^{  
            sleep(6);  
            NSLog(@"op2.....handle..... on 6 thread num%@",[NSThread currentThread]);  
        }];  
          
        [op2 addExecutionBlock:^{  
            sleep(4);  
            NSLog(@"op2.....handle..... on 4 thread num%@",[NSThread currentThread]);  
        }];  
          
        [op2 addExecutionBlock:^{  
            sleep(8);  
            NSLog(@"op2.....handle..... on 8 thread num%@",[NSThread currentThread]);  
        }];  
          
        [op2 addExecutionBlock:^{  
            sleep(1);  
            NSLog(@"op2.....handle..... on 1 thread num%@",[NSThread currentThread]);  
        }];  
        [op2 setCompletionBlock:^{  
            NSLog(@"op2........OK !!");  
        }];  
        [op2 start];  
          
        //bop2  
        NSBlockOperation *bop2 = [NSBlockOperation blockOperationWithBlock:^{  
            sleep(15);  
            NSLog(@"bop2.....handle..... on thread num%@",[NSThread currentThread]);  
        }];  
        [bop2 setCompletionBlock:^{  
            NSLog(@"bop2........OK !!");  
        }];  
        [bop2 start];  
    }  
    

    执行结果:

    
    2017-07-25 13:49:35.830 No.22 Foundation_NSOperation[20740:1443207] block start
    2017-07-25 13:49:39.899 No.22 Foundation_NSOperation[20740:1443307] op2.....handle..... on 4 thread num<NSThread: 0x60800026a780>{number = 4, name = (null)}
    2017-07-25 13:49:40.971 No.22 Foundation_NSOperation[20740:1443307] op2.....handle..... on 1 thread num<NSThread: 0x60800026a780>{number = 4, name = (null)}
    2017-07-25 13:49:41.900 No.22 Foundation_NSOperation[20740:1443254] op2.....handle..... on 6 thread num<NSThread: 0x608000261dc0>{number = 3, name = (null)}
    2017-07-25 13:49:43.902 No.22 Foundation_NSOperation[20740:1443255] op2.....handle..... on 8 thread num<NSThread: 0x60000007df80>{number = 5, name = (null)}
    2017-07-25 13:49:45.832 No.22 Foundation_NSOperation[20740:1443207] op2.....handle..... on 10 hread num<NSThread: 0x60800006e780>{number = 1, name = main}
    2017-07-25 13:49:45.832 No.22 Foundation_NSOperation[20740:1443255] op2........OK !!
    2017-07-25 13:50:00.833 No.22 Foundation_NSOperation[20740:1443207] bop2.....handle..... on thread num<NSThread: 0x60800006e780>{number = 1, name = main}
    2017-07-25 13:50:00.834 No.22 Foundation_NSOperation[20740:1443564] bop2........OK !!
    

    分析下结果:
    首先看到了有1和2两个线程,线程2在56秒的时候开始执行6秒的操作,接下来执行4,1秒结束时间为07秒。线程1在56的时候开始执行10秒的操作,接下来执行8秒,结束时间为14秒。最后执行Bop2的15秒操作至29秒。时间看起来没有问题。为什么会启用2个线程而不是3个或者更多?

    3.接下来介绍NSInvocationOperation

    - (void)invocationOperation  
    {  
        NSInvocationOperation * op3 = [[NSInvocationOperation alloc] initWithTarget:(id)self selector:@selector(handleInvoOpD) object:nil];  
        [op3 setCompletionBlock:^{  
            NSLog(@"op3........OK !!");  
        }];  
        [op3 start];  
    }  
    

    selector函数:

    
    - (void)handleInvoOpD  
    {  
        sleep(5);  
        NSLog(@"op3.....handle.....  on thread num :%@",[NSThread currentThread]);  
    }  
    

    执行结果:

    2017-07-25 13:52:19.661 No.22 Foundation_NSOperation[20766:1446216] op3.....handle.....  on thread num :<NSThread: 0x6000000662c0>{number = 1, name = main}
    2017-07-25 13:52:19.662 No.22 Foundation_NSOperation[20766:1446254] op3........OK !!
    

    NSInvocationOperation比较简单,就是继承了NSOperation,区别就是它是基于一个对象和selector来创建操作,可以直接使用而不需继承来实现自己的操作处理。
    4.最后介绍下NSOperationQueue
    把NSOperation子类的对象放入NSOperationQueue队列中,该队列就会启动并开始处理它。队列里可以加入很多个NSOperation, 可以把NSOperationQueue看作一个线程池,可往线程池中添加操作(NSOperation)到队列中。线程池中的线程可看作消费者,从队列中取走操作,并执行它。
    实现demo:

    - (void)handleOpqueue  
    {  
        NSOperationQueue *qu = [[NSOperationQueue alloc] init];  
          
        NSBlockOperation * bkOp1 = [NSBlockOperation blockOperationWithBlock:^{  
            sleep(10);  
            NSLog(@"bkOp1.....handle.....on thread num%@",[NSThread currentThread]);  
        }];  
        [bkOp1 setCompletionBlock:^{  
            NSLog(@"bkOp1........OK !!");  
        }];  
          
          
        NSBlockOperation * bkOp2 = [NSBlockOperation blockOperationWithBlock:^{  
            sleep(2);  
            NSLog(@"bkOp2.....handle.....on thread num%@",[NSThread currentThread]);  
        }];  
        [bkOp2 setCompletionBlock:^{  
            NSLog(@"bkOp2........OK !!");  
        }];  
          
        NSBlockOperation * bkOp3 = [NSBlockOperation blockOperationWithBlock:^{  
            sleep(1);  
            NSLog(@"bkOp3.....handle.....on thread num%@",[NSThread currentThread]);  
        }];  
        [bkOp3 setCompletionBlock:^{  
            NSLog(@"bkOp3........OK !!");  
        }];  
          
        NSBlockOperation * bkOp4 = [NSBlockOperation blockOperationWithBlock:^{  
            sleep(10);  
            NSLog(@"bkOp4.....handle.....on thread num%@",[NSThread currentThread]);  
        }];  
        [bkOp4 setCompletionBlock:^{  
            NSLog(@"bkOp4........OK !!");  
        }];  
          
        NSBlockOperation * bkOp5 = [NSBlockOperation blockOperationWithBlock:^{  
            sleep(5);  
            NSLog(@"bkOp5.....handle.....on thread num%@",[NSThread currentThread]);  
        }];  
        [bkOp5 setQueuePriority:NSOperationQueuePriorityHigh];  
        [bkOp5 setCompletionBlock:^{  
            NSLog(@"bkOp5........OK !!");  
        }];  
          
        NSInvocationOperation *invoOp6 = [[NSInvocationOperation alloc] initWithTarget:(id)self selector:@selector(handleInvoOp) object:nil];  
        [invoOp6 setCompletionBlock:^{  
            NSLog(@"invoOp6........OK !!");  
        }];  
        [invoOp6 setQueuePriority:NSOperationQueuePriorityHigh];  
          
        [qu setMaxConcurrentOperationCount:2];  
        [qu addOperation:bkOp3];  
        [qu addOperation:bkOp2];  
        [qu addOperation:bkOp1];  
        [qu addOperation:bkOp4];  
        [qu addOperation:bkOp5];  
        [qu addOperation:invoOp6];  
    }  
    

    先看下执行结果:

    2017-07-25 13:53:59.235 No.22 Foundation_NSOperation[20790:1448570] bkOp3.....handle.....on thread num<NSThread: 0x600000266780>{number = 3, name = (null)}
    2017-07-25 13:53:59.236 No.22 Foundation_NSOperation[20790:1448675] bkOp3........OK !!
    2017-07-25 13:54:00.201 No.22 Foundation_NSOperation[20790:1448573] bkOp2.....handle.....on thread num<NSThread: 0x60800026ed80>{number = 4, name = (null)}
    2017-07-25 13:54:00.202 No.22 Foundation_NSOperation[20790:1448573] bkOp2........OK !!
    2017-07-25 13:54:04.311 No.22 Foundation_NSOperation[20790:1448569] bkOp5.....handle.....on thread num<NSThread: 0x6000002733c0>{number = 5, name = (null)}
    2017-07-25 13:54:04.311 No.22 Foundation_NSOperation[20790:1448573] bkOp5........OK !!
    2017-07-25 13:54:05.276 No.22 Foundation_NSOperation[20790:1448570] op3.....handle.....  on thread num :<NSThread: 0x600000266780>{number = 3, name = (null)}
    2017-07-25 13:54:05.277 No.22 Foundation_NSOperation[20790:1448573] invoOp6........OK !!
    2017-07-25 13:54:14.385 No.22 Foundation_NSOperation[20790:1448569] bkOp1.....handle.....on thread num<NSThread: 0x6000002733c0>{number = 5, name = (null)}
    2017-07-25 13:54:14.386 No.22 Foundation_NSOperation[20790:1448573] bkOp1........OK !!
    2017-07-25 13:54:15.349 No.22 Foundation_NSOperation[20790:1448570] bkOp4.....handle.....on thread num<NSThread: 0x600000266780>{number = 3, name = (null)}
    2017-07-25 13:54:15.350 No.22 Foundation_NSOperation[20790:1448573] bkOp4........OK !!
    

    从结果可以看出,NSOperationQueue在2,3,4这3个线程里去处理NSOperation,而不包括主线程1。此外,在设置了bkop5以及invOp6的优先级为高时,他们会优先执行,当然这个优先时相对,是相对正在排队的,不包括已经正在执行的。

    总结:NSOperation、NSBlockOperation、NSInvocationOperation、NSOperationQueue都比较简单,NSOperation、NSBlockOperation、NSInvocationOperation单个都是表示一种操作,而NSOperationQueue是一个可以包含多个NSOperation的队列,可以自己在多个线程处理,只要加入队列之后,我们就不用去操作,直到Callback或者完成。

    相关文章

      网友评论

          本文标题:iOS技术文档No.23 Foundation_NSOperat

          本文链接:https://www.haomeiwen.com/subject/gajwkxtx.html