[摘要]本文介绍iOS NSOperation使用方法,并提供简单的示例代码供参考。
NSOperation的用法:
多线程编程是防止主线程堵塞,增加运行效率等等的最佳方法。而原始的多线程方法存在很多的毛病,包括线程锁死等。在Cocoa中,Apple提供了NSOperation这个类,提供了一个优秀的多线程编程方法。
1) 将想在另外一个线程的工作单独成类,并设置其父类为NSOperation:
1 | @interface ImageLoadingOperation : NSOperation { |
2 | NSURL *imageURL; //这个例子里面需要传入一个图片地址,所以定义一个NSURL变量 |
3 | id target; //由于需要返回一些值,所以需要一个对象参数返回要被返回的对象(运行此线程的类对象) |
4 | SEL action; //返回值要激发的方法函数 |
5 | } |
2)借由其初始化方法来传入所需要的参数和对象
1 | - (id)initWithImageURL:(NSURL *)theImageURL target:(id)theTarget action:(SEL)theAction |
2 | { |
3 | self = [super init]; //在老帖里面解释过为什么需要这么做了 |
4 | if (self) { |
5 | imageURL = [theImageURL retain]; // 拷贝进对象,并retain(为什么?请查老帖) |
6 | target = theTarget; |
7 | action = theAction; |
8 | } |
9 | return self; |
10 | } |
呼叫这个类对象的时候,传入所需要的参数和对象。
1 | // 这些是需要对其初始化的类中的代码 |
2 | ImageLoadingOperation *operation = [[ImageLoadingOperation alloc] initWithImageURL:url target:self action:@selector(didFinishLoadingImageWithResult:)]; //初始化 |
3 | [operationQueue addOperation:operation]; //添加到运行队列 |
4 | [operation release]; //由于队列对其retain,所以我们需要release它 |
3)在我们的线程操作类中的main函数执行所需要的工作
1 | - (void)main |
2 | { |
3 | // 同时载入图片 |
4 | NSData *data = [[NSData alloc] initWithContentsOfURL:imageURL]; |
5 | UIImage *image = [[UIImage alloc] initWithData:data]; |
6 | |
7 | // 打包返回给初始类对象,然后执行其指定的操作 |
8 | NSDictionary *result = [NSDictionary dictionaryWithObjectsAndKeys:image, ImageResultKey, imageURL, URLResultKey, nil]; |
9 | [target performSelectorOnMainThread:action withObject:result waitUntilDone:NO]; |
10 | |
11 | [data release]; //不需要了就清理 |
12 | [image release]; |
13 | } |