NSOperationQueue和NSOperation的使用方法

  1. 首先是建立NSOperationQueue和NSOperations。NSOperationQueue会建立一个线程管理器,每个加入到线程operation会有序的执行。  
  2. NSOperationQueue *queue = [NSOperationQueue new];  
  3. NSInvocationOperation *operation = [[NSInvocationOperation alloc];  
  4. initWithTarget:self  
  5. selector:@selector(doWork:)  
  6. object:someObject];  
  7. [queue addObject:operation];  
  8. [operation release];  
  9. 使用NSOperationQueue的过程:  
  10.     1.  建立一个NSOperationQueue的对象  
  11.     2.  建立一个NSOperation的对象  
  12.     3.  将operation加入到NSOperationQueue中  
  13.     4.  release掉operation  
  14. NSInvocationOperation,NSInvocationOperation是NSOperation的子类,允许运行在operation中的targer和selector  
  15. --------------------------------  
  16.   
  17. 多线程编程是防止主线程堵塞,增加运行效率等等的最佳方法。而原始的多线程方法存在很多的毛病,包括线程锁死等。在Cocoa中,Apple提供了NSOperation这个类,提供了一个优秀的多线程编程方法。  
  18. 本次介绍NSOperation的子集,简易方法的NSInvocationOperation:  
  19. @implementation MyCustomClass  
  20.    
  21. - (void)launchTaskWithData:(id)data  
  22. {  
  23.     //创建一个NSInvocationOperation对象,并初始化到方法  
  24.     //在这里,selector参数后的值是你想在另外一个线程中运行的方法(函数,Method)  
  25.     //在这里,object后的值是想传递给前面方法的数据  
  26.     NSInvocationOperation* theOp = [[NSInvocationOperation alloc] initWithTarget:self  
  27.                     selector:@selector(myTaskMethod:) object:data];  
  28.    
  29.     // 下面将我们建立的操作“Operation”加入到本地程序的共享队列中(加入后方法就会立刻被执行)  
  30.     // 更多的时候是由我们自己建立“操作”队列  
  31.     [[MyAppDelegate sharedOperationQueue] addOperation:theOp];  
  32. }  
  33.    
  34. // 这个是真正运行在另外一个线程的“方法”  
  35. - (void)myTaskMethod:(id)data  
  36. {  
  37.     // Perform the task.  
  38. }  
  39.    
  40. @end  
  41. 一个NSOperationQueue 操作队列,就相当于一个线程管理器,而非一个线程。因为你可以设置这个线程管理器内可以并行运行的的线程数量等等。下面是建立并初始化一个操作队列:  
  42. @interface MyViewController : UIViewController {  
  43.    
  44.     NSOperationQueue *operationQueue;  
  45.     //在头文件中声明该队列  
  46. }  
  47. @end  
  48.    
  49. @implementation MyViewController  
  50.    
  51. - (id)init  
  52. {  
  53.     self = [super init];  
  54.     if (self) {  
  55.         operationQueue = [[NSOperationQueue alloc] init]; //初始化操作队列  
  56.         [operationQueue setMaxConcurrentOperationCount:1];  
  57.         //在这里限定了该队列只同时运行一个线程  
  58.         //这个队列已经可以使用了  
  59.     }  
  60.     return self;  
  61. }  
  62.    
  63. - (void)dealloc  
  64. {  
  65.     [operationQueue release];  
  66.     //正如Alan经常说的,我们是程序的好公民,需要释放内存!  
  67.     [super dealloc];  
  68. }  
  69.    
  70. @end  
  71. 简单介绍之后,其实可以发现这种方法是非常简单的。很多的时候我们使用多线程仅仅是为了防止主线程堵塞,而NSInvocationOperation就是最简单的多线程编程,在iPhone编程中是经常被用到的。
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值