【问题标题】:Asynchronously load UIImage to my data model?将 UIImage 异步加载到我的数据模型中?
【发布时间】:2014-12-28 02:19:18
【问题描述】:

我有一个数据模型,其中包含一个属性,该属性是 UIImages 数组,还有一个属性是 imageURLs 数组(表示相同的图像)。

加载某个视图后,我使用 SDWebImage 使用来自 URLS 的图像填充滚动视图,看起来不错。

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,但我不知道在哪里调用它。

我有这两个属性,因为有些图像来自网络来源,有些来自本地设备/相机。

一个可能的解决方案是,当我最初使用 url 异步加载数据模型时,继续加载 UIImages,但似乎这使用了一大块可能不是需要。因为我要加载多达 20 个项目,所有项目都包含图像数组。

【问题讨论】:

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


    【解决方案1】:

    在 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];
    });
    

    【讨论】:

      猜你喜欢
      • 2012-04-04
      • 2020-01-02
      • 1970-01-01
      • 2016-01-16
      • 1970-01-01
      • 2023-03-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多