views:

86

answers:

3

I've done a lot of research on when it's correct to release things, but it's all confusing to me. I think sometimes the Leaks program is off. Anyway...

background is a UIImageView

background.image = [UIImage imageNamed:@"greenbackground.png"];

Do I have to release background? I never alloced it and it's not set as a property, so I'm thinking no.

A: 

No you don't. That factory method returns an autoreleased UIImage. A good rule of thumb that helps me in objective c is whenever you see alloc, copy or new in a method name... you are incharge of releasing the returned object... everything else should be an autoreleased object. Also, I can't think of any class level methods (+) in the api that don't return autoreleased objects.

EDIT I read your question too quickly... Mark is correct on this. If you are ever in doubt about these kinds of things you can always do a simple test and log the retain count.

Ryan Ferretti
He is asking about releasing "background" the `UIImageView`.
MarkPowell
thanks for the heads up, Mark
Ryan Ferretti
+2  A: 

Actually, you do need to release it.

UIKit uses Key Value Coding to assign IBOutlets to a controller. By default this is causing your controller to increase the retain count by one. From the KeyValueCoding docs:

If you have not defined a setter, then UIKit will directly set the value of the instance variable and then, for anything other than an NSNumber or NSValue date type, UIKit will retain the value after autoreleasing the instance variable’s old value.

Unless you explicitly set a @property with assign, you need to release the object.

MarkPowell
Thanks very much..what if I use that line of code multiple times, do I only have to release it once??if(firstbuttonclicked){background.image = [UIImage imageNamed:@"greenbackground.png"];}else if(secondbuttonclicked){background.image = [UIImage imageNamed:@"redbackground.png"];}
NextRev
No you only release it one time. The retain count is increased on creation of the View, not on assigning the image.
MarkPowell
Ok thank you much
NextRev
A: 

Mark's right that you are responsible for releasing your UIImageView if it is instantiated from a nib, if background is an IBOutlet, and if background does not have a corresponding "assign" property.

Even if you're managing that correctly, you may still see some extra memory in use in ObjectAlloc after you release your UIImageView. That's because -[UIImage imageNamed:] caches the image you load in anticipation of you calling -[UIImage imageNamed:] again later. The image is not necessarily uncached even when the returned UIImage gets deallocated.

Tom
Again, he is asking about "background" which is his UIImageView.
MarkPowell
Thanks; now I see. Edited.
Tom