iphone - 另一款 iPhone - CGBitmapContextCreateImage 泄漏

标签 iphone uiimage memory-leaks

就像这篇文章一样:

我也有类似的问题。 create_bitmap_data_provider 中 malloc 的指针永远不会被释放。我已经验证关联的图像对象最终被释放,而不是提供者的分配。我应该显式创建一个数据提供程序并以某种方式管理它的内存吗?看起来像是黑客攻击。

CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB();
CGContextRef context = CGBitmapContextCreate(NULL, blah blah blah);
CGColorSpaceRelease(colorSpace);

// ... draw into context

CGImageRef imageRef = CGBitmapContextCreateImage(context);
UIImage * image = [[UIImage alloc] initWithCGImage:imageRef];

CGImageRelease(imageRef);
CGContextRelease(context);
<小时/>

在下面的 fbrereto 回答之后,我将代码更改为:

- (UIImage *)modifiedImage {
    CGSize size = CGSizeMake(width, height);

    UIGraphicsBeginImageContext(size);
    CGContextRef context = UIGraphicsGetCurrentContext();

    // draw into context   

    UIImage * image = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();

    return image;  // image retainCount = 1
}    

// caller: 
{
    UIImage * image = [self modifiedImage]; 
    _imageView.image = image; // image retainCount = 2
}

// after caller done, image retainCount = 1, autoreleased object lost its scope

不幸的是,这仍然存在相同的问题,即水平翻转图像的副作用。它似乎在内部对 CGBitmapContextCreateImage 做了同样的事情。

我已验证对象的 dealloc 已被调用。在我释放_imageView之前,_imageView.image_imageView上的retainCount都是1。这确实没有道理。其他人似乎也有这个问题,我是最后一个怀疑 SDK 的人,但是这里是否存在 iPhone SDK 错误???

最佳答案

看起来问题在于您正在释放指向返回的 CGImage 的指针,而不是 CGImage 本身。我之前也遇到过类似的问题,分配量不断增加,最终应用程序崩溃。我通过分配 CGImage 而不是 CGImageRef 来解决这个问题。更改后,在带有分配的 Instruments 中运行代码,您应该不会再看到 malloc 的永久内存消耗。同样,如果您使用类方法imageWithCGImage,您将不必担心稍后自动释放您的UIImage

我在 PC 上输入了此内容,因此如果您将其直接放入 XCode 中,您可能会遇到语法问题,我提前表示歉意;不过校长是健全的。

CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB(); 
CGContextRef context = CGBitmapContextCreate(NULL, blah blah blah); 
CGColorSpaceRelease(colorSpace);

// ... draw into context  

CGImage cgImage = CGBitmapContextCreateImage(context); 
UIImage * image = [UIImage imageWithCGImage:cgImage];  
CGImageRelease(cgImage); 
CGContextRelease(context);
return image;

关于iphone - 另一款 iPhone - CGBitmapContextCreateImage 泄漏,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1434714/

相关文章:

iphone - 导入图像并将其替换为 COCOS2D 中现有的图像

ios - 如何确定 UIImage 使用的字节数?

c++ - 错误 glibc 检测到 free() : invalid next size(fast)

macos - OS X 共享内存清理

java - PermGen 空间错误 - Glassfish 服务器

iPhone CGContext : drawing two lines with two different colors

ios - 后台范围内的iBeacon有时会延迟

iphone - 应用程序激活时删除模态视图 Controller

ios - 'Supporting Files' 文件夹是否会增加启动时间/CPU 消耗?

ios - 使用磁盘中的图像数据填充阵列时崩溃