我有以下代码:
...
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”活动分配的数量在循环的多次迭代中保持不变。
为什么代码会泄漏?我遗漏了什么?
谢谢。
发布于 2011-03-30 14:24:51
您不需要在以下位置保留:
image = [[[UIImage alloc] initWithCGImage: imageRef]] retain];
您正在调用alloc,因此返回的对象的retainCount已经为1。再次保留它会将retainCount递增到2,但在下一次循环迭代上重新分配指针之前,您只需释放它一次。因此,实例泄漏是因为retainCount留在了1。
长话短说,这应该可以解决这个问题:
image = [[UIImage alloc] initWithCGImage: imageRef]];
https://stackoverflow.com/questions/5482622
复制相似问题