Memory leak using 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)] ]; } } } } 

The code compiled above with ARC enabled. The Analyze tool reports a possible memory leak, because imageWithCGImage :: returns a UIImage with count +1, then the link is lost. Leaks Instrument reports no memory leaks. What's going on here?

Also, since ARC prohibits manual use with release ect, how do I fix a leak?

Thanks to everyone who can offer any advice.

+7
source share
2 answers

ARC does not control C types from which CGImage can be considered. You must release ref manually when done with CGImageRelease(image);

 +(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 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); } } } } 
+8
source

None of the data structure master data is considered with ARC. Many times this creates a problem. In this case, we must manually free the memory.

+3
source

All Articles