gpt4 book ai didi

Objective-C imageWithCGImage 内存泄漏

转载 作者:搜寻专家 更新时间:2023-10-30 19:55:28 24 4
gpt4 key购买 nike

我想将 Assets 中的所有照片保存到某个文件夹中。通过以下方式循环执行此操作:

ALAssetRepresentation *representation = [asset defaultRepresentation];
CGImageRef imageRef = [representation fullResolutionImage];

ALAssetOrientation orientation = [representation orientation];
UIImage *image = [UIImage imageWithCGImage:imageRef scale:1.0 orientation:(UIImageOrientation)orientation];

CGFloat compressionQuality = 1.0;
NSData *imageData = [NSData dataWithData:UIImageJPEGRepresentation(image, compressionQuality)];
[imageData writeToFile:path atomically:YES];

CGImageRelease(imageRef);

我启用了自动引用计数。此代码在自动释放池中。它有 CGImageRef 对象的内存泄漏。如果我让

CGImageRelease(imageRef);
CGImageRelease(imageRef);

两次都没有内存泄漏。为什么?任何人都可以帮助我吗?

最佳答案

这是 iOS 中一个令人难以置信的错误。显然,当您使用 imageWithCGImage: 方法创建 UIImage 时,它​​会保留原始的 CGImageRef,即使您释放 UIImage 本身,它也永远不会被释放(例如,如果您使用 ARC,则将其设置为 nil)!所以你必须像这样明确地释放它:

UIImage *image = [UIImage imageWithCGImage:imageRef scale:1.0 orientation:(UIImageOrientation)orientation];
CGImageRelease(imageRef);
...
CGImageRelease(image.CGImage);
image = nil; // once you are done with it

我花了一整天的时间进行挖掘,直到我遇到这个实际上包含答案的问题。我在 Apple 花在调试这个无法形容的错误上的所有时间,我可以向谁发送账单?

更正:这不是 iOS 错误,这是我的愚蠢错误。在某些时候,我通过私有(private)类别“劫持”了 UIImage 的 dealloc 方法来进行一些调试,然后忘记了它。这是错误的做法,因为在这种情况下,实际对象上的 dealloc 永远不会被调用。所以最终结果是意料之中的:UIImage 没有机会做它在被释放时应该做的所有内务处理。永远不要通过私有(private)类别覆盖 dealloc。

关于Objective-C imageWithCGImage 内存泄漏,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7661384/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com