两种方式:1.新线程下载图片,主线程更新视图。代码如下:
[NSThread detachNewThreadSelector:@selector(getImageByUrl:) toTarget:self withObject:array];
-(void)getImageByUrl:(id)object{
NSArray *param=(NSArray*)object;
NSString*imgUrl=[param objectAtIndex:0];
UIImage *image=nil;
NSArray*array=[imgUrl componentsSeparatedByString:@"/"];
NSString*pictName=[array objectAtIndex:[array count]-1];
NSString*imgPath=[NSString stringWithFormat:@"%@%@",BASE_API_URL,imgUrl];
NSURL *url=[NSURL URLWithString:imgPath];
NSData *data=[NSData dataWithContentsOfURL:url];
if (data) {
image=[UIImage imageWithData:data];
[self createImageFileLocal:pictName theData:data];//将图片数据缓存到本地
}else{
image=[UIImage imageNamed:@"xt"];//系统默认图片
}
UIImageView *view =[param objectAtIndex:1];
[view performSelectorOnMainThread:@selector(setImage:) withObject:image waitUntilDone:NO];//主线程更新视图
}
2.采用GCD的方式。代码如下
dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
dispatch_group_t group = dispatch_group_create();
dispatch_group_async(group, queue, ^{
[self loadImage:SCROLL_IMAGE_ONE];//从网络上加载图片1
});
dispatch_group_async(group, queue, ^{
[self loadImage:SCROLL_IMAGE_TWO];//从网络上加载图片1
});
dispatch_group_async(group, queue, ^{
[self loadImage:SCROLL_IMAGE_THREE];//从网络上加载图片1
});
dispatch_group_notify(group, dispatch_get_main_queue(), ^{//三个图片全部加载完毕后更新视图
[self checkImagesArray];
});