Crystal
Crystal

Reputation: 29458

Override copy or copyWithZone: or both?

I'm confused looking at Apple's documentation and reading through Cocoa design patterns. In the Apple documentation for copyWithZone:, it reads:

This method exists so class objects can be used in situations where you need an object that conforms to the NSCopying protocol. For example, this method lets you use a class object as a key to an NSDictionary object. You should not override this method.

For copy it reads:

This is a convenience method for classes that adopt the NSCopying protocol. An exception is raised if there is no implementation for copyWithZone:.

NSObject does not itself support the NSCopying protocol. Subclasses must support the protocol and implement the copyWithZone: method. A subclass version of the copyWithZone: method should send the message to super first, to incorporate its implementation, unless the subclass descends directly from NSObject.

In the examples in Cocoa Design Patterns, they override copyWithZone: and mutableCopyWithZone: but do not override copy when conforming to the NSCopying protocol. Is that what I should do if I want to use my custom subclass in an NSDictionary as a key?

Or do I override copy?

Similarly, if I do [myClass copy], does that call copyWithZone: or copy for that my custom subclass? Thanks.

Upvotes: 8

Views: 3470

Answers (2)

E. Rivera
E. Rivera

Reputation: 10938

You can keep using the superclass convenience method as it is, because it does nothing but call copyWithZone: in any case.

This should be true for any convenience method. You should find out what method they call and override that instead.

Also as said above, zones are no longer used at all but the method still has that parameter for compatibility and historical reasons.

Upvotes: 0

Costique
Costique

Reputation: 23722

It's pretty simple: the default implementation of copy just calls copyWithZone: with a NULL argument. So you should always implement copyWithZone:. However, since memory zones are not used (as far as I know) on iOS, you should ignore the zone without making any assumptions.

Edit: to elaborate, you may implement copy as well, but you must implement copyWithZone: because you never know which of them NSDictionary will call in iOS 6.

Upvotes: 14

Related Questions