#import <Foundation/Foundation.h>
HMDownloadOperation;
HMDownloadOperationDelegate <NSObject>
@optional
- (void)downloadOperation:(HMDownloadOperation *)operation didFinishDownload:(UIImage *)image;
HMDownloadOperation : NSOperation
@property (nonatomic, copy) NSString *imageUrl;
@property (nonatomic, strong) NSIndexPath *indexPath;
@property (nonatomic, weak) id<HMDownloadOperationDelegate> delegate;
@end
#import "HMDownloadOperation.h"
@implementation HMDownloadOperation
- (void)main
{
@autoreleasepool {
if (self.isCancelled) return;
NSURL *url = [NSURL URLWithString:self.imageUrl];
NSData *data = [NSData dataWithContentsOfURL:url]; // 下载
UIImage *image = [UIImage imageWithData:data]; // NSData -> UIImage
if (self.isCancelled) return;
// 回到主线程
[[NSOperationQueue mainQueue] addOperationWithBlock:^{
if ([self.delegate respondsToSelector:@selector(downloadOperation:didFinishDownload:)]) {
[self.delegate downloadOperation:self didFinishDownload:image];
}
}];
}
}
@end