NSOperation的作用 配合使用NSOperation和NSOperationQueue也能实现多线程编程 1、NSOperation和NSOperationQueue实现多线程的具体步骤 2、先将需要执行的操作封装到一个NSOperation对象中 3、然后将NSOperation对象添加到NSOperationQueue中 4、系统会自动将NSOperationQueue中的NSOperation取出来 5、将取出的NSOperation封装的操作放到一条新线程中执行 NSOperation是个抽象类,并不具备封装操作的能力,必须使用它的子类 1、使用NSOperation子类的方式有3种 2、NSInvocationOperation 3、NSBlockOperation 4、自定义子类继承NSOperation,实现内部相应的方法 下面是DEMO @interface CZViewController () /** NSOperation操作队列 */ @property (nonatomic, strong) NSOperationQueue *queue; @end @implementation CZViewController // 将操作添加到队列即可 - (NSOperationQueue *)queue { if (!_queue) _queue = [[NSOperationQueue alloc] init]; return _queue; } - (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event { [self opDemo6]; } /** 暂停操作 */ - (IBAction)pause { // 1. 判断队列中是否有操作 if (self.queue.operationCount == 0) { NSLog(@"没有操作"); return; } // 2. 如果没有被挂起(正在执行),才需要暂停 // 只会挂起当前队列中还没有被调度(没有被安排到线程上工作的操作)才会被挂起 if (!self.queue.isSuspended) { NSLog(@"暂停"); [self.queue setSuspended:YES]; } else { NSLog(@"已经暂停"); } } /** 继续操作 */ - (IBAction)resume { // 1. 判断队列中是否有操作 if (self.queue.operationCount == 0) { NSLog(@"没有操作"); return; } // 2. 如果有被挂起的操作,才需要继续(恢复) if (self.queue.isSuspended) { NSLog(@"继续"); [self.queue setSuspended:NO]; } else { NSLog(@"正在执行"); } } #pragma mark - NSOperation演练 /** 操作之间的依赖 */ - (void)opDemo6 { NSBlockOperation *op1 = [NSBlockOperation blockOperationWithBlock:^{ NSLog(@"正在下载图书 。。。 %@", [NSThread currentThread]); }]; NSBlockOperation *op2 = [NSBlockOperation blockOperationWithBlock:^{ NSLog(@"正在解压缩图书 。。。 %@", [NSThread currentThread]); }]; NSBlockOperation *op3 = [NSBlockOperation blockOperationWithBlock:^{ NSLog(@"正在保存到磁盘 。。。 %@", [NSThread currentThread]); }]; NSBlockOperation *op4 = [NSBlockOperation blockOperationWithBlock:^{ NSLog(@"更新书架(UI),提示用户可以阅读 。。。 %@", [NSThread currentThread]); }]; // 指定操作之间的”依赖“关系,某一个操作的执行,必须等待另一个操作完成才会开始 // 依赖关系是可以跨队列指定的 [op2 addDependency:op1]; [op3 addDependency:op2]; [op4 addDependency:op3]; // *** 添加依赖的时候,注意不要出现循环依赖 // [op3 addDependency:op4]; [self.queue addOperation:op1]; [self.queue addOperation:op2]; [self.queue addOperation:op3]; // 主队列更新UI [[NSOperationQueue mainQueue] addOperation:op4]; } /** 最大并发数 */ - (void)opDemo5 { // 设置队列的最大并发数,队列是负责调度操作的 /** 最大并发数的应用场景: 1> 用户在使用3G的时候 限制线程的数量,省电,省流量(省钱) 2> 用户使用WIFI的时候(局域网) 增加线程数量,提高用户的体验 maxConcurrentOperationCount 如果== 1,类似于串行队列异步方法 */ self.queue.maxConcurrentOperationCount = 1; for (int i = 0; i < 10; i++) { [self.queue addOperationWithBlock:^{ // 模拟休眠 [NSThread sleepForTimeInterval:1.0f]; NSLog(@"正在下载 %@ %d", [NSThread currentThread], i); }]; } } /** Block操作,添加执行块 */ - (void)opDemo4 { // 实例化block操作 NSBlockOperation *op = [[NSBlockOperation alloc] init]; // 设置最大并发(操作)数,不会限制执行块! self.queue.maxConcurrentOperationCount = 2; // 添加执行块 [op addExecutionBlock:^{ NSLog(@"下载书籍1 %@", [NSThread currentThread]); }]; // 继续添加块 [op addExecutionBlock:^{ NSLog(@"下载书籍2 %@", [NSThread currentThread]); }]; // 继续添加块 [op addExecutionBlock:^{ NSLog(@"下载书籍3 %@", [NSThread currentThread]); }]; // 继续添加块 [op addExecutionBlock:^{ NSLog(@"下载书籍4 %@", [NSThread currentThread]); }]; // 继续添加块 [op addExecutionBlock:^{ NSLog(@"下载书籍5 %@", [NSThread currentThread]); }]; // 启动操作,在主线程执行 // 如果执行块的数量超过1,就会自动进入其他线程执行(异步) // 具体开启线程的数量,由系统决定 // 执行块的调度与操作的调度非常像 // [op start]; [self.queue addOperation:op]; } /** 直接添加块操作 */ - (void)opDemo3 { // 只要将操作添加到队列就会立即被调度(执行) for (int i = 0; i < 10; i++) { [self.queue addOperationWithBlock:^{ NSLog(@"下载开始 %@ - %@", [NSThread currentThread], @(i)); }]; } // 向主队列中添加操作 [[NSOperationQueue mainQueue] addOperationWithBlock:^{ NSLog(@"下载开始 %@ - %@", [NSThread currentThread], nil); }]; } /** NSBlockOperation */ - (void)opDemo2 { for (int i = 0; i < 10; i++) { // 指定一个块操作 NSBlockOperation *op1 = [NSBlockOperation blockOperationWithBlock:^{ NSLog(@"下载开始 %@ - %@", [NSThread currentThread], @(i)); }]; // 将块操作添加到队列 [self.queue addOperation:op1]; } } #pragma mark Invocation的调度方法 - (void)download:(id)obj { NSLog(@"下载开始 %@ - %@", [NSThread currentThread], obj); } /** NSInvocationOperation */ - (void)opDemo1 { for (int i = 0; i < 10; i++) { NSInvocationOperation *op1 = [[NSInvocationOperation alloc] initWithTarget:self selector:@selector(download:) object:@(i)]; // 如果直接启动,会在主线程执行 // [op1 start]; // 添加到队列,就会新建线程,异步执行 [self.queue addOperation:op1]; } } @end //头文件 @interface NSOperation : NSObject { - (id)init; // designated initializer //开始任务 - (void)start; - (void)main; //任务是否取消 - (BOOL)isCancelled; - (void)cancel; //是否正在执行 - (BOOL)isExecuting; //是否完成执行 - (BOOL)isFinished; - (BOOL)isConcurrent; - (BOOL)isReady; //队列之间的依赖操作使用的方法 - (void)addDependency:(NSOperation *)op; - (void)removeDependency:(NSOperation *)op; //队列组依赖 - (NSArray *)dependencies; //队列优先级 - (NSOperationQueuePriority)queuePriority; - (void)setQueuePriority:(NSOperationQueuePriority)p; #if NS_BLOCKS_AVAILABLE - (void (^)(void))completionBlock NS_AVAILABLE(10_6, 4_0); - (void)setCompletionBlock:(void (^)(void))block NS_AVAILABLE(10_6, 4_0); #endif //等待直到完成 - (void)waitUntilFinished NS_AVAILABLE(10_6, 4_0); - (double)threadPriority NS_AVAILABLE(10_6, 4_0); - (void)setThreadPriority:(double)p NS_AVAILABLE(10_6, 4_0); @end NS_CLASS_AVAILABLE(10_6, 4_0) @interface NSBlockOperation : NSOperation { @private id _private2; void *_reserved2; } #if NS_BLOCKS_AVAILABLE + (id)blockOperationWithBlock:(void (^)(void))block; - (void)addExecutionBlock:(void (^)(void))block; - (NSArray *)executionBlocks; #endif @end - (id)initWithTarget:(id)target selector:(SEL)sel object:(id)arg; - (id)initWithInvocation:(NSInvocation *)inv; // designated initializer - (NSInvocation *)invocation; - (id)result; @end FOUNDATION_EXPORT NSString * const NSInvocationOperationVoidResultException NS_AVAILABLE(10_5, 2_0); FOUNDATION_EXPORT NSString * const NSInvocationOperationCancelledException NS_AVAILABLE(10_5, 2_0); N - (void)addOperation:(NSOperation *)op; - (void)addOperations:(NSArray *)ops waitUntilFinished:(BOOL)wait NS_AVAILABLE(10_6, 4_0); #if NS_BLOCKS_AVAILABLE - (void)addOperationWithBlock:(void (^)(void))block NS_AVAILABLE(10_6, 4_0); #endif //队列组 - (NSArray *)operations; - (NSUInteger)operationCount NS_AVAILABLE(10_6, 4_0); //最大并发数 - (NSInteger)maxConcurrentOperationCount; - (void)setMaxConcurrentOperationCount:(NSInteger)cnt; enum { NSOperationQueueDefaultMaxConcurrentOperationCount = -1 }; //设置暂停 - (void)setSuspended:(BOOL)b; - (BOOL)isSuspended; //设置名字 - (void)setName:(NSString *)n NS_AVAILABLE(10_6, 4_0); - (NSString *)name NS_AVAILABLE(10_6, 4_0); //取消所有人去 - (void)cancelAllOperations; //等待所有任务完成 - (void)waitUntilAllOperationsAreFinished; //当前队列 + (id)currentQueue NS_AVAILABLE(10_6, 4_0); //主队列 + (id)mainQueue NS_AVAILABLE(10_6, 4_0); @end