views:

1501

answers:

1

Hi all,

I'm working on a game with a bunch of mini games. Inside one gameview, I have the following code:

UIImage* img = [UIImage imageNamed:@"foo.png"];
someImage = CGImageRetain(img.CGImage);
[img release];

someImage is of type CGImageRef, and this has no issues the first time. After the user loses the mini game (or exits), the game and everything seems to get dealloc'd properly. Then, if they go back into the mini game, and the game gets constructed again, the line:

someImage = CGImageRetain(img.CGImage);

causes an error of some kind...almost like my UIImage object got released already. I know there's some quirks to using [UIImage imageNamed], but I can't track this down at all. Any help would be greatly appreciated :)

+10  A: 

This line is your problem;

[img release];

In Cocoa the general convention is that if a function returns an object and does not contain the words copy or alloc then you do not have to release it.

Functions that return objects usually add them to an autorelease pool. If you plan to keep the object then you should retain (and later release) it. If not then it will automatically be freed.

If you try to release one of these objects then it will cause badness. In this case I suspect it's deallocating a resource that the OS believes it still owns.

This thread contains more details about memory management under Cocoa.

Andrew Grant
That seemed to do it...thanks :) One of these days I'll get the hang of which objects I need to keep track of. :)
Jonas