NSOperation下载图片-03

自定义Operation

.h

 1 #import <Foundation/Foundation.h>
 2 @class HMDownloadOperation;
 3 
 4 @protocol HMDownloadOperationDelegate <NSObject>
 5 
 6 @optional
 7 - (void)downloadOperation:(HMDownloadOperation *)operation didFinishDownload:(UIImage *)image;
 8 
 9 @end
10 
11 @interface HMDownloadOperation : NSOperation
12 /**
13  *  图片的url
14  */
15 @property (nonatomic, copy) NSString *imageUrl;
16 
17 /**
18  *  图片所在的行
19  */
20 @property (nonatomic, strong) NSIndexPath *indexPath;
21 
22 /**
23  *  HMDownloadOperation的代理
24  */
25 @property (nonatomic, weak) id<HMDownloadOperationDelegate> delegate;
26 @end

 

.m

 1 #import <UIKit/UIKit.h>
 2 #import "HMDownloadOperation.h"
 3 
 4 @implementation HMDownloadOperation
 5 - (void)main
 6 {
 7     @autoreleasepool {
 8         if(self.isCancelled) return;
 9         
10         NSURL *url = [NSURL URLWithString:self.imageUrl];
11         NSData *data = [NSData dataWithContentsOfURL:url]; // 下载图片
12         UIImage *image = [UIImage imageWithData:data];     // data->image
13         
14         if(self.isCancelled) return;
15         
16         // 回到主线程
17         [[NSOperationQueue mainQueue] addOperationWithBlock:^{
18             if([self.delegate respondsToSelector:@selector(downloadOperation:didFinishDownload:)])
19             {
20                 [self.delegate downloadOperation:self didFinishDownload:image];
21             }
22         }];
23     }
24 }
25 @end

 

posted on 2015-03-17 15:39  FKunLam  阅读(123)  评论(0编辑  收藏  举报