ios - 将 UIImage 异步加载到我的数据模型?

标签 ios model-view-controller model dispatch-async

我有一个数据模型,其中包含一个 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/

相关文章:

ios - UILongPressGestureRecognizer 回调函数的最大频率是多少?

model-view-controller - Ext JS 4 - 理解 this.control、选择器和事件处理

java - Spring 3.2 中 View Body 不显示

google-app-engine - 在 google appengine 数据存储区中建立一种引用自身的模型?

ruby-on-rails - 如何从父模型创建子模型

python - 什么时候在django中调用模型方法

objective-c - 无法访问 appDelegate NSMutableArray 但我可以访问和修改 appDelegate int

cocoa - UINavigationController-Alike for Desktop-Cocoa?

php - 在结果数组中添加参数

c++ - iOS 项目 : If I use C++ (C++11) anywhere in my project, 我必须禁用模块吗?