开发者

A Simple Objective C xcode Memory Management Question

In the code below, will tapsLable.text be deallocated when tapsMessage is released or does the assignment operator somehow increment the retain count so that tapsLabel.text continues to be available?

NSString *tapsMessage = [[NSString alloc] initWithFormat:@"%d taps detected", numTaps];
tapsLabel.text = tapsMessage; // tapsLabel is a UILabel object
[tapsMessage release];
开发者_如何转开发


Here's a tip

You can write the retainCounter for the object then you see what it is before and after the assignment.

e.g. NSLog( @"%d", [tapsMessage retainCount] );

That way you can answer such questions in the future by just writing out the retainCount as it always depends on how the property is declared.


tabsLabel.text is a property on tapsLabel. I think it's a string property that does [target copy] on assignment. Nevermind the details, yes, the assignment operator either increments the retain count or copies the value, so you can release tapsMessage and it is still available in tapsLabel.text.

Read more about properties here.

EDIT: looked up UILabel in the header, yes, it does a copy for the text property.

@property(nonatomic,copy)   NSString       *text;            // default is nil

EDIT: to expand on the important question in the comment

How does anyone know when to release and when not to if you have to look at the implementation details of every object you assign something to?

You just follow the memory management rules. The point of the refcounted environment is exactly that there is some "loose coupling" going on between the objects in terms of memory management. As long as you retain and release properly, it is not your concern whether someone else also retains and releases these same objects, as long as all involved parties have their retains/releases matched.


In the first line, you have allocated and initialised an NSString. You own this object according to the memory management rules, which means you are responsible for releasing it.

In the second line, you are assigning the tapsMessage string the text property. This property (assuming tapsLabel is a UILabel) is declared with the copy attribute. For immutable strings (NSStrings), asking for a copy simply increments the retain count, since there is no need to make an actual duplicate of the data (the data can never change). Since UILabel has made a copy of the string, it has claimed ownership as well (objects can have more than one owner).

In the third line, you relinquish your ownership but the string still has one owner (the label), so the object is not deallocated.


It will not be deallocated.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜