NSMutableString as retain/copy

前端 未结 3 493
花落未央
花落未央 2020-11-28 02:50

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

@property (nonatomic, retain) NSMutableString *str1;

3条回答
  •  被撕碎了的回忆
    2020-11-28 03:42

    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.

提交回复
热议问题