Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Release a retain UIImage property loaded via imageNamed?

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!

like image 920
AlvinfromDiaspar Avatar asked Sep 30 '09 18:09

AlvinfromDiaspar


2 Answers

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
like image 63
sfjava Avatar answered Oct 24 '22 18:10

sfjava


The image is returned to you autoreleased as per the naming rules. Assigning it to a property with a retain attribute via the setter will retain it. Assigning another image to the property via the setter will release the old image and retain the new one.

like image 24
zaph Avatar answered Oct 24 '22 18:10

zaph