【问题标题】:CGImage / UIImage leakCGImage / UIImage 泄漏
【发布时间】:2011-03-30 06:19:28
【问题描述】:

我有以下代码:

...

UIImage *image;
CGImageRef imageRef;

image = [[[UIImage alloc] initWithContentsOfFile: filePath] retain];

while (some_condition)
{
   NSAutoreleasePool *pool = [[NSAutoReleasePool alloc] init];

   imageCGDATA = CGDataProviderCreateWithCFData(cfdata);

   imageRef = CGImageCreate(width, height, bitsPerComponent, bitsPerPixel, bytesPerRow, colorSpace, bitmapInfo, imageCGDATA, NULL, NO, intent);

   CGDataProviderRelease(imageCGDATA);

   [image release];

   image = [[[UIImage alloc] initWithCGImage: imageRef]] retain]; // LEAK HERE

   CGImageRelease(imageRef);

   [pool release];
}

...

当我运行代码并查看分配时,我看到总“实时字节”随着循环的每次迭代完成而增长,并且“CGImage”和“UIImage”实时分配的数量增长到非常大的数字(显然取决于循环的迭代次数)。

如果我注释用“LEAK HERE”注释的代码行(以及该代码行之前的版本)并重新运行应用程序,然后是“Live Bytes”、“CGImage”和“UIImage”的数量在循环的多次迭代中分配保持不变。

为什么该代码会泄漏?我错过了什么?

谢谢。

【问题讨论】:

    标签: iphone objective-c


    【解决方案1】:

    你不需要保留在:

    image = [[[UIImage alloc] initWithCGImage: imageRef]] retain];

    您正在调用 alloc,因此返回的对象的 retainCount 已经为 1。再次保留它会将 retainCount 增加到 2,但在下一个循环中重新分配指针之前您只需释放一次迭代。所以一个实例泄漏是因为retainCount 被保留在 1。

    长话短说,这应该可以解决它:

    image = [[UIImage alloc] initWithCGImage: imageRef]];

    【讨论】:

    • 谢谢!不敢相信我错过了——我是 Objective-C 的新手,我直接忽略了这一点......
    猜你喜欢
    • 2013-01-07
    • 1970-01-01
    • 2014-06-07
    • 2023-03-24
    • 1970-01-01
    • 1970-01-01
    • 2015-02-21
    • 2013-10-26
    • 1970-01-01
    相关资源
    最近更新 更多