iOS NSOperation使用方法简介

来源:互联网 发布:三国志3优化版1.76 编辑:程序博客网 时间:2024/06/05 02:16

[摘要]本文介绍iOS NSOperation使用方法,并提供简单的示例代码供参考。

NSOperation的用法:

多线程编程是防止主线程堵塞,增加运行效率等等的最佳方法。而原始的多线程方法存在很多的毛病,包括线程锁死等。在Cocoa中,Apple提供了NSOperation这个类,提供了一个优秀的多线程编程方法。

1) 将想在另外一个线程的工作单独成类,并设置其父类为NSOperation:

View Row Code
1@interfaceImageLoadingOperation : NSOperation {2NSURL*imageURL; //这个例子里面需要传入一个图片地址,所以定义一个NSURL变量3id target; //由于需要返回一些值,所以需要一个对象参数返回要被返回的对象(运行此线程的类对象)4SEL action; //返回值要激发的方法函数5}

2)借由其初始化方法来传入所需要的参数和对象

View Row Code
1- (id)initWithImageURL:(NSURL*)theImageURL target:(id)theTarget action:(SEL)theAction2{3self= [super init];//在老帖里面解释过为什么需要这么做了4if (self) {5imageURL= [theImageURL retain];// 拷贝进对象,并retain(为什么?请查老帖)6target= theTarget;7action= theAction;8}9return self;10}

呼叫这个类对象的时候,传入所需要的参数和对象。

View Row Code
1// 这些是需要对其初始化的类中的代码2ImageLoadingOperation*operation = [[ImageLoadingOperationalloc]initWithImageURL:url target:self action:@selector(didFinishLoadingImageWithResult:)];//初始化3[operationQueueaddOperation:operation];//添加到运行队列4[operationrelease];//由于队列对其retain,所以我们需要release它

3)在我们的线程操作类中的main函数执行所需要的工作

View Row Code
1- (void)main2{3// 同时载入图片4NSData*data = [[NSDataalloc]initWithContentsOfURL:imageURL];5UIImage*image = [[UIImagealloc]initWithData:data];67// 打包返回给初始类对象,然后执行其指定的操作8NSDictionary*result = [NSDictionarydictionaryWithObjectsAndKeys:image, ImageResultKey, imageURL, URLResultKey, nil];9[targetperformSelectorOnMainThread:action withObject:result waitUntilDone:NO];1011[datarelease];//不需要了就清理12[imagerelease];13}
0 0
原创粉丝点击