iOS-UIImageView加载网络下载的图片(异步+多线程)

最原始的加载网络下载的图片方式:

//最原始加载网络图片方法,相当阻塞主线程,界面卡顿
-(void)setImageWithURL:(NSString *)imageDownloadUrl{
    UIImageView *imageView = [[UIImageView alloc] initWithFrame:CGRectMake(44, 64, 250, 250)];
    NSURL *URL = [NSURL URLWithString:imageDownloadUrl];
    NSError *ERROR;
    NSData *imageData = [NSData dataWithContentsOfURL:URL options:NSDataReadingMappedIfSafe error:&ERROR];
    UIImage *image = [UIImage imageWithData:imageData];
    [imageView setImage:image];
}

使用异步线程加载图片,在加载完成后设置图片,可以在网络加载完成之前,UIimageview先使用占位图片。

//异步线程加载网络下载图片 ——> 回到主线程更新UI
-(void)downloadImageWithUrl:(NSString *)imageDownloadURLStr{
    //以便在block中使用
    __block UIImage *image = [[UIImage alloc] init];
    //图片下载链接
    NSURL *imageDownloadURL = [NSURL URLWithString:imageDownloadURLStr];

    //将图片下载在异步线程进行
    //创建异步线程执行队列
    dispatch_queue_t asynchronousQueue = dispatch_queue_create("imageDownloadQueue", NULL);
    //创建异步线程
    dispatch_async(asynchronousQueue, ^{
        //网络下载图片  NSData格式
        NSError *error;
        NSData *imageData = [NSData dataWithContentsOfURL:imageDownloadURL options:NSDataReadingMappedIfSafe error:&error];
        if (imageData) {
            image = [UIImage imageWithData:imageData];
        }
        //回到主线程更新UI
        dispatch_async(dispatch_get_main_queue(), ^{
            [_imageView setImage:image];
        });
    });
}

如果考虑到线程安全,需要开启自动释放池,此方法同上:

#pragma mark - 下载图片-子线程调用
-(void)downloadImage{

    /**
     子线程里面的runloop默认不开启,也就意味着不会自动创建自动释放池,子线程里面autorelease的对象 就会没有池子释放。也就一位置偶棉没有办法进行释放造成内存泄露
     所以需要手动创建

     */

    @autoreleasepool {

        NSLog(@"%@",[NSThread currentThread]);

        NSURL *url = [NSURL URLWithString:@"http://baidu.com/image/Users/qiuxuewei/Desktop/qiu.JPG"];

        NSData *data = [NSData dataWithContentsOfURL:url];

        UIImage *image0 = [UIImage imageWithData:data];

        UIImage *image = [UIImage imageNamed:@"qiu.JPG"];

        //UI要求在主线程中进行
        //self.imageView.image = image;

       //1、 [self performSelectorOnMainThread:@selector(updataImage:) withObject:image waitUntilDone:NO];
       //2、 [self performSelector:@selector(updataImage:) onThread:[NSThread mainThread] withObject:image waitUntilDone:YES];
        [self.imageView performSelectorOnMainThread:@selector(updataImage:) withObject:image waitUntilDone:YES];

        //waitUntilDone:  表示是否等待子线程方法执行完毕
        //如果是YES:那就等子线程方法执行完再执行当前函数
        NSLog(@"完成..");
    }
}

-(void)updataImage:(UIImage *)image{

    self.imageView.image = image;

}
  • 1
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值