SundayMonday
SundayMonday

Reputation: 19747

Objective-C memory management: What is happening when setting a retain property?

I'd like to understand the memory management implications of the following line of code:

// in tableView:cellForRowAtIndexPath
cell.accessoryView = [[UIImageView alloc] initWithImage:
                      [UIImage imageNamed:@"test.png"];

I'm calling alloc which usually means I call release somewhere. The UITableViewCell's accessoryView setter property is retain so (I think) the cell will "take ownership" of the of the UIImageView. What exactly is happening in the above line of code in regards to memory management?

Upvotes: 0

Views: 231

Answers (3)

Terry Wilcox
Terry Wilcox

Reputation: 9040

Think of it this way: you're calling alloc/init, so you own it. You must release it when you no longer want to own it.

You can assume that cell.accessoryView takes ownership unless the docs say otherwise (like with delegates), so once you assign it to cell.accessoryView, you probably don't need to own it anymore. You should release it.

In summary, that line is retaining at least twice: once with the alloc/init and at least once with the assignment to cell.accessoryView. You are only responsible for one release, the one for alloc/init.

Upvotes: 1

Tim Dean
Tim Dean

Reputation: 8292

If you don't release the view somewhere then it will be leaked. So you might want to do

UIImageView *imageView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"test.png"];
cell.accessoryView = imageView;
[imageView release];

or you could also do

cell.accessoryView = [[[UIImageView alloc] initWithImage:
                  [UIImage imageNamed:@"test.png"] autorelease];

Upvotes: 3

Catfish_Man
Catfish_Man

Reputation: 41821

First: +alloc retains the UIImageView (or, alternately, "you start with ownership of the UIImageView")

Second: +imageNamed autoreleases the UIImage (or, "+imageNamed does not give you ownership of the UIImage")

Third: the setter for accessoryView retains the UIImageView (or, "the accessory view takes ownership of the UIImageView")

Since you now have two owners for the UIImageView, that's probably a leak unless you're intentionally keeping it around to use later, and managing it accordingly.

Upvotes: 2

Related Questions