memory - 使用 ARC 进行 ALAssets 枚举的 iOS 编程内存问题

标签 memory automatic-ref-counting enumeration alassetslibrary

我希望枚举我的专辑,但是当我在我的设备上测试该应用程序时,该应用程序在 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。

提前致谢...

最佳答案

您已经发现 UIImage 对象在创建时会占用大量内存。

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

另外,这一行:

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

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

关于memory - 使用 ARC 进行 ALAssets 枚举的 iOS 编程内存问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20774867/

相关文章:

objective-c - 正确使用ARC(自动引用计数)?

ios - 安全地使用 CFBridgingRelease

python - 在 Python 中使用 enumerate() 将索引旋转回 `for` 循环中的第一个元素的更好方法

c++ - 枚举和指向成员的指针

c++ - strcpy之后的delete[]会不会导致内存泄露?

c - 在 C 中使用 a_list 结构(共享内存中的链表)实现共享内存段

c++ - 带有 PAGE_GUARD 的 VirtualProtect 不使用局部变量

java - 过多使用 LinkedList

ios - ARC - popviewController/DismissViewController

java - 使用 Enumeration<E> 的 hasMoreElements() 和 nextElement() 方法打印列表,第一次成功,添加一些元素后第二次失败