NextRev
NextRev

Reputation: 1711

Does this have to be released?

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.

Upvotes: 2

Views: 138

Answers (3)

Tom
Tom

Reputation: 3861

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.

Upvotes: 0

Ryan Ferretti
Ryan Ferretti

Reputation: 2961

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.

Upvotes: 0

MarkPowell
MarkPowell

Reputation: 16540

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.

Upvotes: 2

Related Questions