标签:
#import "ViewController.h"
@interface ViewController ()
@property (weak, nonatomic) IBOutlet UIImageView *imageView;
@property (nonatomic,strong) NSOperationQueue *queue;
@end
@implementation ViewController
// 懒加载一个非主队列
-(NSOperationQueue *)queue
{
if (!_queue) {
_queue = [[NSOperationQueue alloc] init];
// 设置队列的最大并发数
[_queue setMaxConcurrentOperationCount:6];
}
return _queue;
}
- (void)viewDidLoad {
[super viewDidLoad];
// 自定义 NSOperation
// 自定义步骤: 继承自 NSOperation. 重写 main 方法.
}
- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
// 在子线程下载图片
// 创建操作
__weak typeof(self) wself = self;
NSBlockOperation *op = [NSBlockOperation blockOperationWithBlock:^{
// 下载.
UIImage *image = [self downloadWebImageWithUrlString:@"http://pic1.nipic.com/2008-09-08/200898163242920_2.jpg"];
// 回到主线程显示图片
[[NSOperationQueue mainQueue] addOperationWithBlock:^{
NSLog(@"显示图片%@",[NSThread currentThread]);
// 显示图片
wself.imageView.image = image;
}];
}];
// 将操作添加到非主队列中
[self.queue addOperation:op];
// 在主线程显示图片
}
// 下载网络图片的方法
- (UIImage *)downloadWebImageWithUrlString:(NSString *)urlString
{
NSLog(@"downloadWebImageWithUrlString:%@",[NSThread currentThread]);
NSURL *url = [NSURL URLWithString:urlString];
NSData *data = [NSData dataWithContentsOfURL:url];
UIImage *image = [UIImage imageWithData:data];
return image;
}
@end
标签:
原文地址:http://www.cnblogs.com/R-X-L/p/4782665.html