开发者

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?


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜