Henley Wing Chiu
Henley Wing Chiu

Reputation: 22515

iPhone: How Memory works when adding to subview

A general question: When you add an item to an UIView, does that increase the owner count by 1? Does the main view that you added the item to now becomes an owner as well?

Example:

mainView = [[UIView alloc] init];
UILabel *label = [[UILabel alloc] init];
[mainView addSubview:label] //does this increase owner count by 1?
[label release] //and this decreases it by 1?

Upvotes: 1

Views: 132

Answers (2)

Jonathan.
Jonathan.

Reputation: 55544

You release what you retain/init.

When you call addSubview:, it increases the retain count (or as you say owner count). But that increase belongs to mainView. So it is up to mainView to release the subview some point in the future, not you.

So when you init the label it increases the retain count to 1. When you call addSubview:label it increases the retain count by 1, to 2. Then you release the label, decreasing the retain count back to 1 and counteracting you're previous init.

Then when the label is removed from the mainView its retain count will go back down to 0 and it will be deallocated.

Never use the method retainCount, whether you're just observing it, or acting on it. This method will not display what you expect because of a lot of behind the scenes code. Just don't use retainCount.

Upvotes: 3

TechZen
TechZen

Reputation: 64428

Subviews are stored in a NSArray which sends a retain to every object added. In principle, yes the retain count goes as you expect but in reality you can never observe the retain count reliably because of all the retains and releases that occur behind the scenes in the API itself. Trying to track the retain count directly will just lead to grief.

It's better to just follow the rule of if you create an object with new or alloc-init then you release it. If you don't do the former, you don't do the later.

Upvotes: 1

Related Questions