Release a retain UIImage property loaded via imageNamed?

AlvinfromDiaspar picture AlvinfromDiaspar · Sep 30, 2009 · Viewed 7.2k times · Source

In my class object i've defined a (nonatomic, retain) property for UIImage. I assigned this property with an image loaded via

[UIImage imageNamed:@"file.png"];

If at some point I want to reassign this property to another image, should I have to release the prior reference?

I am confused because by the retain property I know i should release it. But because imageNamed: is a convenience method (does not use alloc), im not sure what rule to apply here.

Thanks for the insight!

Answer

sfjava picture sfjava · May 27, 2010

Correct, Florin... but per the discussion above, if one is using a setter for the property that (either via synthesize, or manually) does the "retain", then there's no need for the extra retain.

In other words, the following would be correct (and free of memory-leaks), IMHO, am I right? I think this was the original intent of the question... and I'd also like to be certain. ;-) thx!

@interface MyClass {
    UIImage *myImage;
}
@property (nonatomic, retain) UIImage *myImage;
@end

@implementation MyClass
@synthesize myImage;

- (void) someMethod {

    self.myImage = [UIImage imageNamed:@"foo.png"];
}

- (void) someOtherMethod {

    self.myImage = [UIImage imageNamed:@"bar.png"];
}

- (void) dealloc {

    self.myImage = nil;
    [super dealloc];
}
@end