【问题标题】:iOS Programming memory issue with ALAssets enumeration with ARC使用 ARC 枚举 ALAssets 的 iOS 编程内存问题
【发布时间】:2013-12-25 16:43:55
【问题描述】:

我希望枚举我的相册,但是当我在我的设备上测试应用程序时,应用程序在 30 秒后崩溃。当我使用 Instrument 时,我发现 ARC 不会自动释放资产,因此每次处理图像时,它都会分配图像大小。我的主要目标是只显示设备的屏幕截图。所以假设我有 1000 张照片,在 30 张图片之后我得到 30MB 分配,这会导致崩溃。如何显式释放内存?

这是我的代码:

[self.assetsGroup enumerateAssetsUsingBlock:^(ALAsset *result, NSUInteger index, BOOL *stop) {

    if (result) {

        ALAssetRepresentation* representation = [result defaultRepresentation];

        // Retrieve the image orientation from the ALAsset
        UIImageOrientation orientation = UIImageOrientationUp;

        NSNumber* orientationValue = [result valueForProperty:@"ALAssetPropertyOrientation"];

        if (orientationValue != nil) {
            orientation = [orientationValue intValue];
        }

        CGFloat scale  = 1;
        UIImage* image = [UIImage imageWithCGImage:[representation fullResolutionImage]
                                             scale:scale orientation:orientation];

        if ( image.size.height/2==screenHeight && image.size.width/2==screenWidth)
            [self.assets addObject:result];
    }
}];

我认为默认表示会导致 malloc。

提前谢谢...

【问题讨论】:

  • 在将 ALAsset 添加到资产数组后立即尝试“image = nil;”会发生什么?
  • 试过了,但没有用。可能是由于强类型问题。

标签: memory automatic-ref-counting enumeration alassetslibrary


【解决方案1】:

您发现 UIImage 对象在创建时会占用 很多 内存。

为什么不使用 ALAsset 提供给您的不占用内存的 API,而不是创建 UIImage 对象。例如,您可以获取图片dimensions(我已为您链接了 Apple 文档)。

另外,这一行:

if ( image.size.height/2==screenHeight && image.size.width/2==screenWidth)

对我来说似乎有点危险。除非您控制正在加载的所有图像,否则任何全分辨率图像的大小很可能与屏幕高度和宽度的 1/2 不同。

【讨论】:

  • 尺寸绝对有效!谢谢迈克尔。我只需要截图,它们的尺寸等于设备的尺寸。
  • @Michael 你有关于你声称 ALAsset* 不占用内存的参考资料吗?谢谢!
  • 嗨@AlexSpencer; ALAsset 对象只是一个指向(有时是巨大的)UIImage 文件的对象。 ALAsset 对象本身包含属性,如果我们真的想学究气,也许defaultRepresentation 是相当大的it's a "ALAssetRepresentation" object
  • 实际上,自从 iOS 8 引入了新的 Photos framework 取代 ALAsset 的东西以来,所有这些都是旧消息。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2016-02-23
  • 1970-01-01
  • 1970-01-01
  • 2023-03-13
  • 2015-07-09
  • 2013-01-10
  • 1970-01-01
相关资源
最近更新 更多