PDA

View Full Version : Proper way to re-use property?




shawnl
Sep 19, 2008, 07:29 PM
I have a UIImage property which I need to be able to change the UIImage on the fly.

Currently I do this like so...

if (activeImage != nil)
{
[activeImage release];
activeImage = nil;
}

activeImage = image;

The problem I have noticed is as soon as I call the release it shows FREEID(id) in the debugger popup where it used to show UIImage *... so I am thinking that this is not the correct way to release the old resources before filling the new ones... suggestions are appreciated!



robbieduncan
Sep 20, 2008, 05:42 AM
If that is the entirety of the method why not just synthesize the accessors? That way you can guarantee it's correct.

Otherwise iirc this is the "correct" way:


- (void) setImage:(UIImage *) theImage
{
UIImage *temp;
if (theImage != image) // This avoids a retain/release cycle if we are trying to set the same image as currently is in use.
{
temp = image; // I have assumed the property is called image
image = [theImage retain]; // We can message nil objects so this should be fine
[temp release];
}
}

Nutter
Sep 20, 2008, 12:06 PM
There's no need for a temporary variable if you're checking that the objects aren't identical.

Sbrocket
Sep 20, 2008, 03:11 PM
As Nutter mentioned there, the temp var isn't necessary.


- (void) setImage:(UIImage *) theImage {
if (theImage != image) {
[image release];
image = [theImage retain];
}
}

robbieduncan
Sep 20, 2008, 03:16 PM
Just a bit of a tweak, robbie. :)

I believe that's what Nutter said above...

Sbrocket
Sep 20, 2008, 03:30 PM
I believe that's what Nutter said above...

Yes, it is what Nutter said, so I simply posted the change in case someone not quite sure what he meant came across the thread. Is that ok with you? :rolleyes: