主線程直接這樣調(diào)用加載網(wǎng)絡(luò)圖片泉懦,網(wǎng)絡(luò)不好時(shí)候會(huì)出現(xiàn)圖片卡頓稿黍,體驗(yàn)非常不好
UIImage * xprodImg = [UIImage imageWithData:[NSData dataWithContentsOfURL:[NSURL URLWithString:services.xprodImg]]];
于是考慮利用NSOperationQueue來(lái)異步加載圖片:
- (void)viewDidLoad
{
[super viewDidLoad];
operationQueue = [[NSOperationQueue alloc] init];
self.imageView = [[[UIImageView alloc] initWithFrame:CGRectMake(110, 50, 100, 100)] autorelease];
self.imageView.layer.masksToBounds = YES;
self.imageView.layer.cornerRadius = 5.0f;
[self.imageView setBackgroundColor:[UIColor grayColor]];
[self.view addSubview:self.imageView];
NSInvocationOperation *op = [[NSInvocationOperation alloc] initWithTarget:self selector:@selector(downloadImage) object:nil];
[operationQueue addOperation:op];
}
- (void)downloadImage
{
NSURL *imageUrl = [NSURL URLWithString:IMAGE_URL];
UIImage *image = [UIImage imageWithData:[NSData dataWithContentsOfURL:imageUrl]];
self.imageView.image = image;
}
2、多線程異步處理常用代碼
dispatch_async(dispatch_get_global_queue(0, 0), ^{
// 處理耗時(shí)操作的代碼塊...
//通知主線程刷新
dispatch_async(dispatch_get_main_queue(), ^{
//回調(diào)或者說(shuō)是通知主線程刷新崩哩,
});
});