标签:
NSOperation可以调用start方法来执行任务,但默认是同步执行的,如果将NSOperation添加到 NSOperationQueue(操作队列)中,系统会自动异步执行队列中的操作。
NSOperationQueue中可以对操作进行取消,暂停和恢复
取消函数为:
-
- (void)cancelAllOperations;
也可以调用NSOperation的cancel方法来取消单个操作
队列中有个属性 suspended
,通过设置该BOOL值的YES或NO来暂停和恢复操作。
操作也有优先级,通过设置NSOperation在队列中的优先级,可以改变操作的执行优先级,NSOperation中有个属性queuePriority,
可以通过该属性来设置,优先级的取值都有
NSOperationQueuePriorityVeryLow = -8L,
NSOperationQueuePriorityLow = -4L,
NSOperationQueuePriorityNormal = 0,
NSOperationQueuePriorityHigh = 4,
NSOperationQueuePriorityVeryHigh = 8
NSOperation中具备一个非常常用的属性,该属性在头文件中得定义如下
-
@property (copy) void (^completionBlock)(void) NS_AVAILABLE(10_6, 4_0);
通过该属性我们可以进行操作的监听,当该操作执行完毕后,就会执行completionBlock中的块代码,例如:
-
-
NSBlockOperation *op = [NSBlockOperation blockOperationWithBlock:^{
-
[NSThread sleepForTimeInterval:3.0];
-
NSLog(@"%@ , come here",[NSThread currentThread]);
-
}];
-
-
NSOperationQueue *queue = [[NSOperationQueue alloc] init];
-
-
[queue addOperation:op];
-
-
[op setCompletionBlock:^{
-
[[NSOperationQueue mainQueue] addOperationWithBlock:^{
-
NSLog(@"%@,here",[NSThread currentThread]);
-
}];
-
-
}];
效果如下:
无论执行什么操作,块代码总会在最后执行!
NSoperation之间可以设置依赖来保证执行顺序,例如:
-
NSBlockOperation *op1 = [NSBlockOperation blockOperationWithBlock:^{
-
NSLog(@"用户登录 %@", [NSThread currentThread]);
-
}];
-
NSBlockOperation *op2 = [NSBlockOperation blockOperationWithBlock:^{
-
NSLog(@"付费 %@", [NSThread currentThread]);
-
}];
-
NSBlockOperation *op3 = [NSBlockOperation blockOperationWithBlock:^{
-
[NSThread sleepForTimeInterval:1.0f];
-
NSLog(@"下载 %@", [NSThread currentThread]);
-
}];
-
NSBlockOperation *op4 = [NSBlockOperation blockOperationWithBlock:^{
-
NSLog(@"更新UI %@", [NSThread currentThread]);
-
}];
-
-
-
-
-
-
-
[op2 addDependency:op1];
-
-
[op3 addDependency:op2];
-
-
[op4 addDependency:op3];
-
-
-
-
[self.queue addOperations:@[op1, op2, op3] waitUntilFinished:NO];
-
-
-
[[NSOperationQueue mainQueue] addOperation:op4];
-
-
NSLog(@"come here");
执行效果如下:
ios多线程操作(十一)—— NSOperation的高级操作
标签:
原文地址:http://blog.csdn.net/wuwuweiweilonglong/article/details/51167225