多线程之NSOperation

Posted on 2012-03-17 00:51  无忧consume  阅读(217)  评论(0编辑  收藏  举报

多线程之NSOperation

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

  1. @interface ImageLoadingOperation : NSOperation {
  2.     //需要传入一个图片地址,所以定义一个NSURL变量
  3.     NSURL *imageURL;
  4.     //由于需要返回一些值,所以需要一个对象参数返回要被返回的对象(运行此线程的类对象)
  5.     id target;
  6.     //返回值要激发的方法函数
  7.     SEL action; 
  8. }
复制代码

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

  1. - (id)initWithImageURL:(NSURL *)theImageURL target:(id)theTarget action:(SEL)theAction
  2. {
  3.     self = [super init];
  4.     if (self) {
  5.         //拷贝进对象,并retain
  6.         imageURL = [theImageURL retain];
  7.         target = theTarget;
  8.         action = theAction;
  9.     }
  10.     return self;
  11. }
复制代码

初始化这个类的时候,传入所需要的参数和对象

  1. //这些是需要对其初始化的类中的代码
  2. //初始化
  3. ImageLoadingOperation *operation = [[ImageLoadingOperation alloc] initWithImageURL:url target:self action:@selector(didFinishLoadingImageWithResult:)];  
  4. //添加到运行队列
  5. [operationQueue addOperation:operation];
  6. //由于队列对其retain,所以需要release它
  7. [operation release];
复制代码

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

  1. - (void)main
  2. {
  3.     //载入图片
  4.     NSData *data = [[NSData alloc] initWithContentsOfURL:imageURL];
  5.     UIImage *image = [[UIImage alloc] initWithData:data];
  6.     //打包返回给初始类对象,然后执行其指定的操作
  7.     NSDictionary *result = [NSDictionary dictionaryWithObjectsAndKeys:image, ImageResultKey, imageURL, URLResultKey, nil];
  8.     [target performSelectorOnMainThread:action withObject:result waitUntilDone:NO];
  9.     [data release]; 
  10.     [image release];
  11. }
复制代码

这些就是一个简单的NSOperation的使用过程

Copyright © 2024 无忧consume
Powered by .NET 8.0 on Kubernetes