For some reason, the retain/release behavior in the following code has me completely baffled.
selectedImage = [UIImage imageNamed:@"icon_72.png"];
[selectedImage release];
This should break but does not. Why? I thought imageNamed autoreleased itself which means the release here is redundant and should break when the autorelease occurs.
Here are snippets relevant to selectedImage from the .h and .m files:
@property (nonatomic, readonly) UIImage *selectedImage;
@synthesize delegate, selectedImage, spacerBottom, currentIndex;
Other notes, this does break:
selectedImage = [UIImage imageNamed:@"icon_72.png"];
[selectedImage release];
[selectedImage release];
//objc[55541]: FREED(id): message release sent to freed object=0x59245b0
//Program received signal: “EXC_BAD_INSTRUCTION”.
As does this:
selectedImage = [UIImage imageNamed:@"icon_72.png"];
[selectedImage release];
[selectedImage autorelease];
//objc[55403]: FREED(id): message autorelease sent to freed object=0x59b54c0
//Program received signal: “EXC_BAD_INSTRUCTION”.
And so does the following:
selectedImage = [UIImage imageNamed:@"icon_72.png"];
[selectedImage autorelease];
[selectedImage release];
//objc[55264]: FREED(id): message release sent to freed object=0x592c9a0
//Program received signal: “EXC_BAD_INSTRUCTION”.
And so does this:
selectedImage = [UIImage imageNamed:@"icon_72.png"];
[selectedImage autorelease];
[selectedImage autorelease];
//objc[55635]: FREED(id): message release sent to freed object=0x5b305d0
//Program received signal: “EXC_BAD_INSTRUCTION”.
-imageNamed: returns an autoreleased image, which, as deanWombourne says, will be autoreleased at some time in the future (the exact time is undefined).
The reason it’s not being autoreleased as early as you are perhaps used to is that -imageNamed also caches the image it returns. The cache is retaining the image.
So essentially, the retain cycle is something like this:
If you do not release it, the cache will continue to retain the image until it releases it, for instance when a memory warning occurs. So when you get an image using imageNamed, it doesn’t get deallocated, until the cache is purged.
Hope this clears things up.