多线程 之 NSOperation

链接地址:http://c.gzl.name/archives/137

多线程 之 NSOperation

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

本次讲解NSOperation的使用方法:

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

@interface ImageLoadingOperation : NSOperation {

    NSURL *imageURL; //这个例子里面需要传入一个图片地址,所以定义一个NSURL变量

    id target; //由于需要返回一些值,所以需要一个对象参数返回要被返回的对象(运行此线程的类对象)

    SEL action; //返回值要激发的方法函数

}

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

- (id)initWithImageURL:(NSURL *)theImageURL target:(id)theTarget action:(SEL)theAction

{

    self = [super init]; //在老帖里面解释过为什么需要这么做了

    if (self) {

        imageURL = [theImageURL retain]; // 拷贝进对象,并retain(为什么?请查老帖)

        target = theTarget;

        action = theAction;

    }

    return self;

}

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

// 这些是需要对其初始化的类中的代码

ImageLoadingOperation *operation = [[ImageLoadingOperation alloc] initWithImageURL:url target:self action:@selector(didFinishLoadingImageWithResult:)];  //初始化

[operationQueue addOperation:operation]; //添加到运行队列

[operation release];  //由于队列对其retain,所以我们需要release它

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

- (void)main

{

    // 同时载入图片

    NSData *data = [[NSData alloc] initWithContentsOfURL:imageURL];

    UIImage *image = [[UIImage alloc] initWithData:data];

 

    // 打包返回给初始类对象,然后执行其指定的操作

    NSDictionary *result = [NSDictionary dictionaryWithObjectsAndKeys:image, ImageResultKey, imageURL, URLResultKey, nil];

    [target performSelectorOnMainThread:action withObject:result waitUntilDone:NO];

 

    [data release]; //不需要了就清理

    [image release];

}

这些就是一个简单的NSOperation的使用过程了。其实看看嘛,非常简单的,正如苹果为我们准备的其他API一样!

你可能感兴趣的:(Opera)