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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With