Problem with sprite sheet
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开发者_JS百科.
Since you haven’t posted the declaration of imgSprite
, I’ll assume that its class follows Cocoa naming conventions.
In:
CGImageRef imgRef = [imgSprite CGImage];
that method (a non-NARC1 method) returns an object that you do not own, hence you should not release it.
In:
[imgView setImage:[UIImage imageWithCGImage:CGImageCreateWithImageInRect(imgRef, CGRectMake(column*width, line, width, height))]];
the argument is the expression:
CGImageCreateWithImageInRect(imgRef, CGRectMake(column*width, line, width, height))
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:
CGImageRelease(imgRef);
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 imgRef
and you’re leaking the image returned by CGImageCreateWithImageInRect()
.
You should do the following instead:
// you do not own imgRef, hence you shouldn’t release it
CGImageRef imgRef = [imgSprite CGImage];
// use a variable for the return value of CGImageCreateWithImageInRect()
// because you own the return value, hence you should release it later
CGImageRef imgInRect = CGImageCreateWithImageInRect(imgRef, CGRectMake(column*width, line, width, height));
[imgView setImage:[UIImage imageWithCGImage:imgInRect]];
CGImageRelease(imgInRect);
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.
精彩评论