Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 936
copenndthagen Avatar asked Feb 14 '11 17:02

copenndthagen


1 Answers

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.

like image 153
Abizern Avatar answered Sep 17 '22 15:09

Abizern