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

提问和评论都可以,用心的回复会被更多人看到
评论
发布评论
相关文章