开发者

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

开发者 https://www.devze.com 2023-03-30 06:54 出处:网络
I\'d like to understand the memory management implications of the following line of code: // in tableView:cellForRowAtIndexPath

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 U开发者_如何学JAVAIImageView. What exactly is happening in the above line of code in regards to memory management?


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];


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.


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消