Copy and mmutable objects


#1

I’m a little confused about the third paragraph on page 81. It reads:

To me this seems to contradict itself. It says it wasteful to make a copy, but then it says it implements copy. Is this a mistake? If not, can anyone provide a little clarification? Thanks!


#2

If you have a property like so:

@property (nonatomic, copy) NSString *name;

Then someone could write this code:

NSMutableString *myName = [NSMutableString stringWithString:@"Christian"];
self.name = myName;

Since NSMutableString is a kind of NSString, then you want to use copy so that if someone uses a mutable subclass, an immutable copy is created (an NSString in this case).

Additionally, immutable subclasses essentially optimize out copy messages, so while it is wasteful in theory to copy an immutable class, in practice there is no effect.