标签:多线程 ios objective-c nsoperation
NSOperation有两种方法:
1>.NSInvocationOperation:创建一个operation,并用selecter指向执行的代码段
2>.NSBlockOperation:创建一个operation,并将执行的代码放在block块中.
1.NSInvocationOperation多线程方法:
创建方法:
- (void)invocationOperation { NSInvocationOperation *operation1 = [[NSInvocationOperation alloc] initWithTarget:self selector:@selector(run1) object:nil]; NSOperationQueue *queue = [[NSOperationQueue alloc] init]; [queue addOperation:operation1]; }
- (void)run1{ NSLog(@"runing1---%@",[NSThread currentThread]); }
2.NSBlockOperation多线程方法:
创建方法:
- (void)blockOperation1 { NSBlockOperation *operation = [NSBlockOperation blockOperationWithBlock:^{ NSLog(@"blockOperation---%@",[NSThread currentThread]); }]; operation.completionBlock = ^{ NSLog(@"finish!-----"); }; NSOperationQueue *queue = [[NSOperationQueue alloc] init]; [queue addOperation:operation]; }
3.从子线程回到主线程刷新UI方法:
performSelectorOnMainThread: withObject: waitUntilDone:
4.多个operation在queue中的执行顺序是可以设置的.
在添加到queue之前设定operation之间的依赖关系:
[operation2 addDependency:operation1];operation2依赖于operation1=>2在1的后边执行.此时如果queue中只有2个operation的话不会多创建一个子线程的,进程中只有主线程和operation1的那个子线程.毕竟顺序执行多开一个子线程是浪费的嘛.
5.queue中可以设定同时最多的线程数量
queue.maxConcurrentOperationCount = 3;
--end
版权声明:本文为博主原创文章,转载请注明来源:http://blog.csdn.net/zhangwenhai001
标签:多线程 ios objective-c nsoperation
原文地址:http://blog.csdn.net/zhangwenhai001/article/details/46762677