iOS NSOperation使用方法简介
来源:互联网 发布:三国志3优化版1.76 编辑:程序博客网 时间:2024/06/05 02:16
[摘要]本文介绍iOS NSOperation使用方法,并提供简单的示例代码供参考。
NSOperation的用法:
多线程编程是防止主线程堵塞,增加运行效率等等的最佳方法。而原始的多线程方法存在很多的毛病,包括线程锁死等。在Cocoa中,Apple提供了NSOperation这个类,提供了一个优秀的多线程编程方法。
1) 将想在另外一个线程的工作单独成类,并设置其父类为NSOperation:
1@interfaceImageLoadingOperation : NSOperation {2NSURL*imageURL; //这个例子里面需要传入一个图片地址,所以定义一个NSURL变量3id target; //由于需要返回一些值,所以需要一个对象参数返回要被返回的对象(运行此线程的类对象)4SEL action; //返回值要激发的方法函数5}
2)借由其初始化方法来传入所需要的参数和对象
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}
呼叫这个类对象的时候,传入所需要的参数和对象。
1// 这些是需要对其初始化的类中的代码2ImageLoadingOperation*operation = [[ImageLoadingOperationalloc]initWithImageURL:url target:self action:@selector(didFinishLoadingImageWithResult:)];//初始化3[operationQueueaddOperation:operation];//添加到运行队列4[operationrelease];//由于队列对其retain,所以我们需要release它
3)在我们的线程操作类中的main函数执行所需要的工作
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
- iOS NSOperation使用方法简介
- ios多线程 -- NSOperation 简介
- NSOperation简介
- iOS NSOperation
- iOS NSOperation
- iOS NSOperation
- ios NSoperation
- ios-NSOperation
- iOS NSOperation
- 猫猫学iOS(五十三)多线程网络之NSOperation简介
- iOS开发之多线程-- NSOperation使用简介(个人笔记)
- AJ学IOS(53)多线程网络之NSOperation简介
- NSOperation(操作)简介
- 多线程之NSOperation简介
- NSOperationQueue和NSOperation的使用方法
- NSOperationQueue和NSOperation的使用方法
- NSOperationQueue和NSOperation的使用方法
- NSOperationQueue和NSOperation的使用方法
- Android 中LayoutInflater的inflate函数用法详解
- C#高级编程(5) Array .Sort()、IComparable 、IComparer
- Tomcat中temp文件夹出现项目副本问题的解决方法
- Appium(Java)2.0.0以上运行时报错“java.lang.UnsupportedClassVersionError: io/appium/java_client/AppiumDriver”
- 【LeetCode】Best Time to Buy and Sell Stock III
- iOS NSOperation使用方法简介
- 任务调度
- java验证码--待抽象
- Linux网络层 ip_rcv()函数代码分析(__pskb_pull_tail)
- ubuntu 设置打开文件的默认方式
- 【问题集合】开发过程中遇到的问题
- jsp 上传Excel文件
- Codeforces Round #277.5 (Div. 2) D——Unbearable Controversy of Being
- JS全局变量