Override copy or copyWithZone: or both?
Asked Answered
P

2

8

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.

Paestum answered 14/2, 2012 at 16:18 Comment(0)
M
14

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.

Mame answered 14/2, 2012 at 18:2 Comment(0)
R
0

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.

Running answered 15/10, 2015 at 14:28 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.