NSOperation
NSOperation是苹果在gcd的基础上封装的一层,更好的处理和控制大量的并发操作,但是速度比gcd慢。NSOperationqueue会自动处理线程的优先级,在复杂的线程中,NSOperation更加方便。
使用方式:1.系统提供的子类,2.自定义子类
1.系统提供的子类
NSOperationQueue *queue = [[NSOperationQueue alloc]init]; NSBlockOperation *operation = [NSBlockOperation blockOperationWithBlock:^{ NSData *data = [[NSData alloc]initWithContentsOfURL:[NSURL URLWithString:@"http://d.hiphotos.baidu.com/image/pic/item/9922720e0cf3d7ca60432a7df41fbe096b63a907.jpg"]]; dispatch_async(dispatch_get_main_queue(), ^{ _imageback.image = [UIImage imageWithData:data]; }); }]; //添加第二个队列 [operation addExecutionBlock:^{ NSData *data = [[NSData alloc]initWithContentsOfURL:[NSURL URLWithString:@"http://d.hiphotos.baidu.com/image/pic/item/9922720e0cf3d7ca60432a7df41fbe096b63a907.jpg"]]; dispatch_async(dispatch_get_main_queue(), ^{ _imageback2.image = [UIImage imageWithData:data]; }); }]; [queue addOperation:operation];//异步线程 // [operation start];//同步 // [operation cancel];//同步 [operation setCompletionBlock:^{ NSLog(@"over");//执行完成之后的回调 }];
2.自定义子类
通过在另一个页面中完成操作,将完成的操作结果通过delegate来发送到主页面。
其他操作:
NSOperationQueue *queue = [[NSOperationQueue alloc]init]; NSBlockOperation *operation = [NSBlockOperation blockOperationWithBlock:^{ NSData *data = [[NSData alloc]initWithContentsOfURL:[NSURL URLWithString:@"http://d.hiphotos.baidu.com/image/pic/item/9922720e0cf3d7ca60432a7df41fbe096b63a907.jpg"]]; dispatch_async(dispatch_get_main_queue(), ^{ _imageback.image = [UIImage imageWithData:data]; }); }]; [queue addOperation:operation];//异步线程 [operation setCompletionBlock:^{ NSLog(@"over");//执行完成之后的回调 }]; NSBlockOperation *operation2 = [NSBlockOperation blockOperationWithBlock:^{ NSData *data = [[NSData alloc]initWithContentsOfURL:[NSURL URLWithString:@"http://d.hiphotos.baidu.com/image/pic/item/9922720e0cf3d7ca60432a7df41fbe096b63a907.jpg"]]; dispatch_async(dispatch_get_main_queue(), ^{ _imageback2.image = [UIImage imageWithData:data]; }); }]; [queue addOperation:operation2]; [operation addDependency:operation2];//添加依赖,操作1依赖于操作2,操作2完成后开始操作1
//修改操作的优先级 operation.queuePriority = NSOperationQueuePriorityLow; operation2.queuePriority = NSOperationQueuePriorityVeryHigh; //修改最大并发数 queue.maxConcurrentOperationCount = 1; [operation waitUntilFinished];//等待线程完成之后继续执行,会阻塞线程 queue.suspended = YES;//暂停队列 只会暂停后面新添加的队列,但是对前面已经添加的队列无效。 queue.suspended = NO;//继续队列