objective-ccocoaretainnscopyingcopywithzone

NSCopying and copyWithZone: - should they return [self retain] or something else?


I'm having a hard time understanding copyWithZone.

I know it's supposed to return a copy, but if I add an object to a dictionary, it adds a 'copyWithZone' object to the dictionary. If I make an actual copy (that is, a new object), then the object added to the dictionary will not be the same object. However, if I only increase the retain count, then it's not technically a copy.

Should I just retain self, or make an actual copy?


Solution

  • copyWithZone: is supposed to return an immutable object (if there are immutable and mutable versions of the class). If the original is immutable, simply retaining & returning the original would be safe, since none of the owners could mutate the object. Otherwise (i.e. original is mutable or the immutable/mutable dichotomy doesn't apply), return a copy.

    As for NSDictionary and NSMutableDictionary, generally only the keys are copied (items are only copied if you explicitly say to with -initWithDictionary:copyItems:), which is necessary as the internal data structure of the dictionary depends on the key values. If you were to mutate a key being used by a dictionary, it would corrupt the dictionary's data structure and you would no longer be able to retrieve the item for that key, or worse.