ios 多线程加载图片

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];
            });
        });


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值