iOS自定义NSOperation
1.步骤:
重写- (void)main方法,在里面实现想执行的操作(例如图片下载等耗时操作)
2.注意点
1》自己创建自动释放池
2》 通过- (BOOL)isCancelled方法检测操作是否被取消,对取消做出响应
3.下面我们简单以图片下载为例自定义一个NSOpeartion ,LLDownloadOperation
LLDownloadOperation.h
@class LLDownloadOperation; @protocol DownloadOperationDelegate <NSObject> @optional -(void)downloadOperation:(LLDownloadOperation *)operation didFineshDownloadImage:(UIImage *)image; @end //自定义要继承子NSOperation @interface LLDownloadOperation : NSOperation ///下载的链接 @property (nonatomic,copy) NSString *urlStr; ///代理 @property (nonatomic,assign) id <DownloadOperationDelegate> delegate; @end
LLDownloadOperation.m
#import "LLDownloadOperation.h" @implementation LLDownloadOperation -(void)main{ @autoreleasepool { //自己创建自动释放池 if (self.isCancelled) return; //通过- (BOOL)isCancelled方法检测操作是否被取消 NSURL *url=[NSURL URLWithString:self.urlStr]; NSData *data=[NSData dataWithContentsOfURL:url]; if (self.isCancelled) return; //通过- (BOOL)isCancelled方法检测操作是否被取消 if(data!=nil){ UIImage *image=[UIImage imageWithData:data]; //通知代理 if ([self.delegate respondsToSelector:@selector(downloadOperation:didFineshDownloadImage: withIndexPath:)]) { dispatch_async(dispatch_get_main_queue(), ^{ [self.delegate downloadOperation:self didFineshDownloadImage:image withIndexPath:self.indexPath]; }); } } } } @end
LLDownloadOperation *operation=[[LLDownloadOperation alloc] init]; operation.urlStr=url; operation.delegate=self; self.queue.maxConcurrentOperationCount=2; [self.queue addOperation:operation]; //异步下载 -(NSOperationQueue *)queue{ if (!_queue) { _queue=[[NSOperationQueue alloc] init]; } return _queue; } #pragma mark - DownloadOperation Delegate -(void)downloadOperation:(LLDownloadOperation *)operation didFineshDownloadImage:(UIImage *)image{ NSLog(@“%@“,image); }