Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
471 views
in Technique[技术] by (71.8m points)

iphone - NSMutableString as retain/copy

I have aa number of NSMutableString's in my app (almost 10-11); all defined as ivar/property

@property (nonatomic, retain) NSMutableString *str1;

I read somewhere that it is better to use "copy" for strings. Is that true? If yes, can I just replace retain to copy in my app and remove the release in dealloc ?

Do I need to consider some other things as well ?

Also, is it normal to have 10-11 NSMutableString's in 1 app..I mean from memory usage perspective ? I also have 4-5 NSMutableDictionary's as well in my app. Please let me know if that is fine.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

While Taskinoor's answer is correct, I'd like to add a bit more explanation.

The recommendation is to use copy for classes that are part of a class cluster that have mutable/immutable pairs; such as NSString/NSMutableString NSArray/NSMutableArray NSDictionary/NSMutableDictionary NSSet/NSMutableSet

The reason for this is that it is possible to have a property that is declared as an immutable type (such as NSString) yet pass it a mutable type (such as NSMutableString). In which case it is possible to change the property from outside the class as Taskinoor describes.

Using copy is recommended, because it behaves sensibly with class clusters. sending copy to a mutable class returns an immutable copy of the object (i.e. sending a copy message to an NSMutableString returns an NSString). But, sending copy to an immutable counterpart is equivalent to sending it a retain message.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...