多线程之初识NSOperation

首先,看到多线程我们会优先想起GCD.之前被提问.有了GCD为什么还要封装NSOperation?相信百度是有很多答案,但是,在我看来NSOperation,新增的属性,操作依赖让我们使用起来更方便,更加贴近面向对象的程序设计思想.

今天只是简单的介绍下如何自定义NSOperation.大致思想如下:
多线程之初识NSOperation_第1张图片
Snip20161122_1.png

1.如果是自定义,前提是你自定义的类,一定也是继承自NSOperation.

@interface MyOperation : NSOperation

2.在NSOperation中有一个类,如果没有实现它,默认他是什么也不做. 你可以重写次方法,实现你自己需要做的操作.官方文档解释如下:
The default implementation of this method does nothing. You should override this method to perform the desired task. In your implementation, do not invoke super. This method will automatically execute within an autorelease pool provided by NSOperation, so you do not need to create your own autorelease pool block in your implementation.
If you are implementing a concurrent operation, you are not required to override this method but may do so if you plan to call it from your custom start method.
这段文章自己看的也是一知半解,如有不同意见,请下方留言!

- (void) main {

NSURL *url = [NSURL URLWithString:self.urlStr];
NSData *data = [NSData dataWithContentsOfURL:url];
UIImage *img = [UIImage imageWithData:data];

[[NSOperationQueue mainQueue] addOperationWithBlock:^{
   
    self.finishedBlock(img);
}];  
}

3.最后一步,也就是实例化对象.你需要懒加载一个队列.将操作添加进队列.

   MyOperation *op = [[MyOperation alloc]init];
op.urlstr = urlstr;
//实现
op.finishedBlock = ^(UIImage *img){
    self.MyImageView.image = img;
};
//把操作对象添加到队列中 最终会调用main方法
[self.queue addOperation:op];

以上纯属复习之前所学内容,整理的相当简单.仅供参考

你可能感兴趣的:(多线程之初识NSOperation)