您的位置:首页 > 移动开发 > IOS开发

ios 多线程加载图片

2015-05-29 10:09 351 查看
NSThread异步加载图片
-(void)downloadImage:(NSIndexPath *)indexPath
{
@autoreleasepool {
……
UIImage * image = [UIImage imageWithData:data];
if(image != nil){
[self.imagesCache replaceObjectAtIndex:indexPath.row withObject:image];
}
//更新UI的代码须到主线程中执行
[self performSelectorOnMainThread:@selector(updateTableViewCellImage:) withObject:indexPath waitUntilDone:NO];
}
}

NSOperationQueue异步加载图片

-(void)main{
if (![self isCancelled]) {
NSLog(@"start");
NSData *data = [NSURLConnection sendSynchronousRequest:self.request returningResponse:nil error:nil];
self.image = [[UIImage imageWithData:data]retain];
if (self.delegate) {
[self.delegate imageLoadedForIndexPath:self.indexPath withImage:self.image];
}
}
}

// Configure the cell...
UIImage *image =  (UIImage *)[self.imgDic objectForKey:[NSString stringWithFormat:@"%d",indexPath.row]];
if (!image) {
image = self.avatarImage;
[self.imgDic setObject:image forKey:[NSString stringWithFormat:@"%d",indexPath.row]];
//起一个线程,去下载图片
ImageLoader *loader = [[[ImageLoader alloc]initWithUrl:[self.sourceUrlArray objectAtIndex:indexPath.row] andIndexPath:indexPath]autorelease];
loader.delegate = self;
[self.queue addOperation:loader];
}
cell.imageView.image = image;

GCD异步加载图片

//启动线程,下载图片,下载完成后放入缓存数组中
dispatch_async(dispatch_get_global_queue(0, 0), ^{
……
UIImage * image = [UIImage imageWithData:data];
if(image != nil){
[self.imagesCache replaceObjectAtIndex:indexPath.row withObject:image];
}
//下载完成后转到主线程更新表格cell
dispatch_async(dispatch_get_main_queue(), ^{
UITableViewCell * cell = [self.tableView cellForRowAtIndexPath:indexPath];
UIImageView * imageView = (UIImageView *)[cell.contentView viewWithTag:111];
imageView.image = [self.imagesCache objectAtIndex:indexPath.row];
});
});
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: