NSMutableString as retain/copy

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.

Leave a Comment