深入学习NSOperationQueue

目前在 iOS 有两套先进的多线程同步 API 可供我们使用NSOperation 和 GCD 。其中 GCD 是基于 C 的底层的 API ,而 NSOperation 则是 GCD 实现的 Objective-C API。

为何推荐NSOperationQueue

如果GCD那么我们的网络请求数据的方法应该是这样的

dispatch_async(_Queue, ^{ //请求数据 NSData *data = [NSData dataWithContentURL:[NSURL URLWithString:@”http://domain.com/a.png”]];dispatch_async(dispatch_get_main_queue(), ^{//回去主线程刷新UI});});

整体来说代码简洁度看着还是比较优雅,但是仔细看就会发现,本请求是无法cancel的,紧接而来的蛋疼问题就多了你觉得呢?

那么我们就需要解决这令人上火的问题,自然NSOprationQueue就成了GCD的替代品,那么NSOprationQueue的优势到底在哪里?

优势:

NSOperationQueue的使用

NSOperationQueue有两种不同的队列

自定义队列主队列

自定义队列在后台执行,主队列在主线程执行 任务队列有两种:

NSBlockOperationNSInvocationOperation

他们都继承自 NSOperation。他们的用法应该是这样的:

*NSBlockOperation*

NSOperationQueue *queue = [[NSOperationQueue alloc] init]; //自定义队列NSBlockOperation *operation = [NSBlockOperation blockOperationWithBlock:^{//任务执行}];[queue addOperation:operation];

* NSInvocationOperation*

NSOperationQueue *queue = [[NSOperationQueue alloc] init]; //自定义队列NSInvocationOperation *operation = [[NSInvocationOperation alloc] initWithTarget:self selector:@selector(_SEL) object:nil];[queue addOperation:operation];

Queue的一个属性maxConcurrentOperationCount ,我们可以通过设这个数来限制queue的并行还是串行队列,当maxConcurrentOperationCount = 1时候为串行队列,否则为并行队列。

NSOperation

如果我们用这个就必须继承自NSOperation,然后重写main方法,顺便有个更为令人惊喜的事情就是,,重写的NSOperation是可以cancel掉正在执行的Operation的,这样就便于我们操作NSOperation的各种非正常状态如:莫名卡死之类的BUG

使用 main 方法非常简单,开发者不需要管理一些状态属性当 main 方法返回的时候,这个 operation 就结束了。

@implementation YourOperation- (void)main{ @autoreleasepool {// 任务代码 …}}@end

接受自己的失败面,是一种成熟,更是一种睿智

深入学习NSOperationQueue

相关文章:

你感兴趣的文章:

标签云: