首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >CGImage / UIImage泄漏

CGImage / UIImage泄漏
EN

Stack Overflow用户
提问于 2011-03-30 14:19:28
回答 1查看 729关注 0票数 1

我有以下代码:

代码语言:javascript
复制
...

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“的代码行(以及该行代码之前的版本)并重新运行应用程序,那么"Live Bytes”、"CGImage“和"UIImage”活动分配的数量在循环的多次迭代中保持不变。

为什么代码会泄漏?我遗漏了什么?

谢谢。

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2011-03-30 14:24:51

您不需要在以下位置保留:

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

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

长话短说,这应该可以解决这个问题:

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

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/5482622

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档