1.新建一个类 继承于NSOperation,重写-(void)main方法。值得注意的是main方法是系统自动调用的
2.在子线程中 操作网络获取图片的操作,并用block方式将网络上获取的图片传递给主线程的控制器。
-(void)main{
NSURL*url = [NSURLURLWithString:self.URLString];
NSData*data = [NSDatadataWithContentsOfURL:url];
UIImage*image = [UIImageimageWithData:data];
if(self.myBlock) {
self.myBlock(image);
}
}
3.在主线程中修改UI界面。对获获取自定义的blockOpera方法进行了封装
-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent*)event{
NSLog(@"123");
NSOperationQueue*operaQueue = [[NSOperationQueuealloc]init];
CYWOperation*blockOpera = [CYWOperationinitWithOperation:@"http://b.hiphotos.baidu.com/image/h%3D200/sign=7a9f8d984f36acaf46e091fc4cd88d03/bd3eb13533fa828b176e5342f91f4134960a5ac6.jpg"withBlock:^(UIImage*image) {
self.imageView.image= image;
}];
[operaQueueaddOperation:blockOpera];
}
封装方法
+ (instancetype)downLoadImageWithURLString:(NSString*)URLString successBlock:(void(^)(UIImage*))successBlock{
HMDownLoadImageOperation*downLoadImageOperation = [[HMDownLoadImageOperationalloc]init];
downLoadImageOperation.innerURLString= URLString;
downLoadImageOperation.innerSuccessBlock= successBlock;
returndownLoadImageOperation;
}
网友评论