NSOperationQueue和NSOperation的使用方法
首先是建立NSOperationQueue和NSOperations。NSOperationQueue會(huì)建立一個(gè)線程管理器,每個(gè)加入到線程operation會(huì)有序的執(zhí)行。
- NSOperationQueue *queue = [NSOperationQueue new];
- NSInvocationOperation *operation = [[NSInvocationOperation alloc];
- initWithTarget:self
- selector:@selector(doWork:)
- object:someObject];
- [queue addObject:operation];
- [operation release];
使用NSOperationQueue的過程:
1. 建立一個(gè)NSOperationQueue的對(duì)象
2. 建立一個(gè)NSOperation的對(duì)象
3. 將operation加入到NSOperationQueue中
4. release掉operation
NSInvocationOperation,NSInvocationOperation是NSOperation的子類,允許運(yùn)行在operation中的targer和selector
多線程編程是防止主線程堵塞,增加運(yùn)行效率等等的最佳方法。而原始的多線程方法存在很多的毛病,包括線程鎖死等。在Cocoa中,Apple提供了NSOperation這個(gè)類,提供了一個(gè)優(yōu)秀的多線程編程方法。
本次介紹NSOperation的子集,簡(jiǎn)易方法的NSInvocationOperation:
- @implementation MyCustomClass
- - (void)launchTaskWithData:(id)data
- {
- //創(chuàng)建一個(gè)NSInvocationOperation對(duì)象,并初始化到方法
- //在這里,selector參數(shù)后的值是你想在另外一個(gè)線程中運(yùn)行的方法(函數(shù),Method)
- //在這里,object后的值是想傳遞給前面方法的數(shù)據(jù)
- NSInvocationOperation* theOp = [[NSInvocationOperation alloc] initWithTarget:self
- selector:@selector(myTaskMethod:) object:data];
- // 下面將我們建立的操作“Operation”加入到本地程序的共享隊(duì)列中(加入后方法就會(huì)立刻被執(zhí)行)
- // 更多的時(shí)候是由我們自己建立“操作”隊(duì)列
- [[MyAppDelegate sharedOperationQueue] addOperation:theOp];
- }
- // 這個(gè)是真正運(yùn)行在另外一個(gè)線程的“方法”
- - (void)myTaskMethod:(id)data
- {
- // Perform the task.
- }
- @end
一個(gè)NSOperationQueue 操作隊(duì)列,就相當(dāng)于一個(gè)線程管理器,而非一個(gè)線程。因?yàn)槟憧梢栽O(shè)置這個(gè)線程管理器內(nèi)可以并行運(yùn)行的的線程數(shù)量等等。下面是建立并初始化一個(gè)操作隊(duì)列:
- @interface MyViewController : UIViewController {
- NSOperationQueue *operationQueue;
- //在頭文件中聲明該隊(duì)列
- }
- @end
- @implementation MyViewController
- - (id)init
- {
- self = [super init];
- if (self) {
- operationQueue = [[NSOperationQueue alloc] init]; //初始化操作隊(duì)列
- [operationQueue setMaxConcurrentOperationCount:1];
- //在這里限定了該隊(duì)列只同時(shí)運(yùn)行一個(gè)線程
- //這個(gè)隊(duì)列已經(jīng)可以使用了
- }
- return self;
- }
- - (void)dealloc
- {
- [operationQueue release];
- //正如Alan經(jīng)常說的,我們是程序的好公民,需要釋放內(nèi)存!
- [super dealloc];
- }
- @end
簡(jiǎn)單介紹之后,其實(shí)可以發(fā)現(xiàn)這種方法是非常簡(jiǎn)單的。很多的時(shí)候我們使用多線程僅僅是為了防止主線程堵塞,而NSInvocationOperation就是最簡(jiǎn)單的多線程編程,在iPhone編程中是經(jīng)常被用到的。




















