内存泄漏和ARC
内存泄漏和ARC
+(void)setup { UIImage* spriteSheet = [UIImage imageNamed:@"mySpriteSheet.png"]; CGRect rect; animation = [NSMutableArray arrayWithCapacity:numberOfFramesInSpriteSheet]; int frameCount = 0; for (int row = 0; row < numberFrameRowsInSpriteSheet; row++) { for (int col = 0; col < numberFrameColsInSpriteSheet; col++) { frameCount++; if (frameCount <= numberOfFramesInSpriteSheet) { rect = CGRectMake(col*frameHeight, row*frameWidth, frameHeight, frameWidth); [animation addObject:[UIImage imageWithCGImage:CGImageCreateWithImageInRect(spriteSheet.CGImage, rect)] ]; } } } }
启用ARC编译上述代码。分析工具报告可能存在内存泄漏,因为imageWithCGImage::返回计数+1的UIImage,然后引用丢失。泄漏工具未报告任何内存泄漏。这里发生了什么?
此外,由于ARC禁止手动使用release
等,如何修复泄漏?
感谢任何能提供帮助的人。
admin 更改状态以发布 2023年5月20日
\n\nARC不管理C类型,其中可以考虑CGImage。当您完成后必须手动释放引用CGImageRelease(image);
\n\n
+(void)setup { UIImage* spriteSheet = [UIImage imageNamed:@"mySpriteSheet.png"]; CGRect rect; animation = [NSMutableArray arrayWithCapacity:numberOfFramesInSpriteSheet]; int frameCount = 0; for (int row = 0; row < numberFrameRowsInSpriteSheet; row++) { for (int col = 0; col < numberFrameColsInSpriteSheet; col++) { frameCount++; if (frameCount <= numberOfFramesInSpriteSheet) { rect = CGRectMake(col*frameHeight, row*frameWidth, frameHeight, frameWidth); //store our image ref so we can release it later //The create rule says that any C-interface method with "create" in it's name //returns a +1 foundation object, which we must release manually. CGImageRef image = CGImageCreateWithImageInRect(spriteSheet.CGImage, rect) //Create a UIImage from our ref. It is now owned by UIImage, so we may discard it. [animation addObject:[UIImage imageWithCGImage:image]]; //Discard the ref. CGImageRelease(image); } } } }