开发者

Retain Count in Copy property

please read the following code::

AddressCard *card1 = [[AddressCard alloc] init]; 
AddressCard *card2 = [[AddressCard alloc] init];

[card1 setName:[NSMutableString stringWithString:@"Deepak"] andEmail:[NSMutableString stringWithString:@"开发者_C百科deepak@paymate"]];

NSMutableString * temp = [NSMutableString stringWithString:@"Deepak"];
r1 = [temp retainCount];
r2 = [card1.name retainCount];

//[card2 setName:card1.name];//retain count 2
//OR//
[card2 setName:temp];// retain count 1

r1 = [card2.name retainCount];

this is some think confusing because in both cases input type is string.

Thanks in advance. d


You as a programmer dont need to worry about the exact value of the retain count (mostly). You need to keep a track of which objects are owned by others.

In your code where you get the retain counts r1 & r2....

Nothing owns temp , it was created with a class method (+ method) so it will get released at next autorelease pool flush .

card1 owns its "name"

when you set [card2 setName:temp]; thats when card2 owns temp. It is no longer under threat of being detroyed at next pool release.


I think you seem to be missing the point of mutable and immutable objects. When you invoke setName:andEmail: is there any logical reason why this method expects mutable strings? For example, does this method change the values of these strings by inserting or removing characters? They only need to be mutable if you intend to change the contents of the string. If you are only assigning the strings to another variable and not modifying the string's actual content, then they should be immutable NSStrings instead.

Also, if you are confused about when to retain and when to release objects, please make sure that you have read and understood the Cocoa Memory Management Programming Guide. This will likely answer any questions that you have about what methods/properties will retain objects and also when you should release objects.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜