您的位置:首页 > 运维架构

自定义NSOperation 操作

2015-12-03 00:00 204 查看
摘要: operation 都会在main 这个方法中执行

#import <Foundation/Foundation.h>

@class HMDownloadOperation;

@protocol HMDownloadOperationDelegate <NSObject>
@optional
- (void)downloadOperation:(HMDownloadOperation *)operation didFinishDownload:(UIImage *)image;
@end

@interface 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
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: