我有一个数据模型,其中包含一个 UIImage 数组属性和一个 imageURL 数组属性(代表相同的图像)。
加载某个 View 后,我使用 SDWebImage 使用来自 URLS 的图像填充 ScrollView ,这看起来不错。
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...
}
我的问题是,如何在不锁定 UI 的情况下同时将这些 UIIamges 加载到我的数据模型 (self.project.images) 中。我假设它是某种 dispatch_async,但我不知道在哪里调用它。
我有这两个属性,因为一些图像来自网络资源,一些来自本地设备/相机。
一个可能的解决方案是,当我最初使用 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];
});
关于ios - 将 UIImage 异步加载到我的数据模型?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26680147/