The code below shows how I’m cutting my sprites, but the memory usage grows constantly. How can I fix?
CGImageRef imgRef = [imgSprite CGImage];
[imgView setImage:[UIImage imageWithCGImage:CGImageCreateWithImageInRect(imgRef, CGRectMake(column*width, line, width, height))]];
CGImageRelease(imgRef);
This code is called by the NSTimer in an interval of 0.1.
Since you haven’t posted the declaration of
imgSprite, I’ll assume that its class follows Cocoa naming conventions.In:
that method (a non-NARC1 method) returns an object that you do not own, hence you should not release it.
In:
the argument is the expression:
CGImageCreateWithImageInRect()(a function whose name follows the Create Rule2) returns an image that you do own, hence you should release it, which you don’t.In:
you’re releasing an image that you do not own, so you should not release it.
You have two problems: you’re (potentially over)releasing
imgRefand you’re leaking the image returned byCGImageCreateWithImageInRect().You should do the following instead:
You might want to read the Memory Management Programming Guide and the Memory Management Programming Guide for Core Foundation.
1NARC = new, alloc, retain, copy
2The Create Rule states that if you call a function whose name contains Create or Copy then you own the return value, hence you should release it when you don’t need it any longer.