//
// ViewController.m
// NSBlockOperation
//
// Created by yons on 10/23/18.
// Copyright © 2018 yons. All rights reserved.
//
#import "ViewController.h"
@interface ViewController ()
@property (weak, nonatomic) IBOutlet UIImageView *iv;
@end
NSOperationQueue* queue;
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
queue = [[NSOperationQueue alloc]init];
queue.maxConcurrentOperationCount = 10;
}
- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event{
NSString* url = @"http://img.zcool.cn/community/0117e2571b8b246ac72538120dd8a4.jpg@1280w_1l_2o_100sh.jpg";
// 以传入的代码块作为执行体,创建NSOperation
NSBlockOperation* operation = [NSBlockOperation
blockOperationWithBlock:^{
// 从网络获取数据
NSData *data = [[NSData alloc]
initWithContentsOfURL:[NSURL URLWithString:url]];
// 将网络数据初始化为UIImage对象
UIImage *image = [[UIImage alloc]initWithData:data];
if(image != nil)
{
// // 主线程方法 1
// 在主线程中执行updateUI:
// [self performSelectorOnMainThread:@selector(updateUI:)
// withObject:image waitUntilDone:YES];
// 主线程方法 2
// [[NSOperationQueue mainQueue] addOperationWithBlock:^{
//
// self.iv.image = image;
// NSLog(@"UI---%@",[NSThread currentThread]);
// }];
// 主线程方法 3
dispatch_async(dispatch_get_main_queue(), ^{
self.iv.image = image;
});
}
else
{
NSLog(@"---下载图片出现错误---");
}
}];
[queue addOperation:operation];
}
-(void)updateUI:(UIImage*) image
{
self.iv.image = image;
}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
@end
网友评论