[英]Asynchronously load UIImage to my data model?
我有一个数据模型,该模型包含一个属性,该属性是一个UIImages数组,另一个属性是一个imageURLs数组(代表相同的图像)。
加载某个视图后,我使用SDWebImage使用URL中的图像填充了一个滚动视图,看起来不错。
for (NSURL *url in self.project.imageURLs) {
UIImageView *imageView = [[UIImageView alloc]init];
[imageView setImageWithURL:[NSURL URLWithString:urlString] placeholderImage:[UIImage imageNamed:@"loading"] usingActivityIndicatorStyle:UIActivityIndicatorViewStyleGray];
[imageView setContentMode:UIViewContentModeScaleAspectFit];
[self.scrollview addSubview:imageView];
...some other frame calculations...
}
我的问题是,我如何同时将这些UIIamges加载到我的数据模型(self.project.images)中而不锁定UI。 我假设这是某种dispatch_async,但我不知道该在哪里调用。
我同时具有这两个属性,因为某些图像来自Web来源,而某些图像来自本地设备/相机。
一种可能的解决方案是,当我最初使用url异步加载数据模型时,可以继续并在那时加载UIImages,但是似乎正在使用可能不需要的大量内存。 由于我正在加载多达20个项目,所有项目均包含图像阵列。
在Swift 4.2中:使用这种方式
DispatchQueue.main.async {
// loading data, adding to an array, setting an image to UIImageView
}
内存管理版本:
DispatchQueue.main.async {[weak weakSelf = self] in
// loading data, adding to an array, setting an image to UIImageView
// use weakSelf to avoid a memory leak: weakSelf.project.images ...
// best way is to create a method in your ViewController – self.updateImage(), and call in this dispatch
}
objC版本:
__weak typeof(self) weakSelf = self;
dispatch_async(dispatch_get_main_queue(), ^{
// use weakSelf here to avoid memory leaking like this:
// [weakSelf updateImageView: indexOfImage];
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.