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

干宏邈
2023-12-01

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

//最原始载入网络图片方法,相当堵塞主线程,界面卡顿
-(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;

}
 类似资料: