ios多线程操作(十二)—— 自定义NSOperation实现网络下载后回调
#import <UIKit/UIKit.h> @interface CXWebImageOperation : NSOperation /** * 实例化web图片操作 */ + (instancetype)webImageOperationWithUrl:(NSString *)urlString completion:(void(^) (UIImage *image))completion; @end
@interface CXWebImageOperation () /** * 图片的url */ @property (nonatomic,copy) NSString *urlString; /** * 下载完图片后需要执行的代码块 */ @property (nonatomic,copy) void (^completion)(UIImage *image); @end
+ (instancetype)webImageOperationWithUrl:(NSString *)urlString completion:(void(^) (UIImage *image))completion { CXWebImageOperation *op = [[self alloc] init]; op.urlString = urlString; op.completion = completion; return op; }
- (void)main { @autoreleasepool { // 下载图片的耗时操作 NSURL *url = [NSURL URLWithString:self.urlString]; NSData *data = [NSData dataWithContentsOfURL:url]; NSLog(@"已下载 %@",[NSThread currentThread]); UIImage *image = [UIImage imageWithData:data]; // 主线程回调,完成操作后通知调用方完成回调 dispatch_async(dispatch_get_main_queue(), ^{ if (self.completion != nil) { self.completion(image); } }); } }
@interface ViewController () /** * 图片 */ @property (weak, nonatomic) IBOutlet UIImageView *iconV; /** * 操作队列 */ @property (nonatomic,strong) NSOperationQueue *queue; @end
- (NSOperationQueue *)queue { if (_queue == nil) { _queue = [[NSOperationQueue alloc] init]; } return _queue; }
- (void)viewDidLoad { [super viewDidLoad]; // 图片下载操作 CXWebImageOperation *op = [CXWebImageOperation webImageOperationWithUrl:@"http://p17.qhimg.com/dr/48_48_/t012d281e8ec8e27c06.png" completion:^(UIImage *image) { NSLog(@"%@",[NSThread currentThread]); // block回调在主线程更新UI self.iconV.image = image; }]; // 添加进队列 [self.queue addOperation:op]; }
郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。