1

Firstly I would like confirmation that I have understood NSCopying correctly ...

In order to use a simple NSObject subclass as a key in an NSDictionary I must have it implement the NSCopying protocol. In the copied instance's copyWithZone method I must alloc/init a new instance of my class, set its properties to be identical to the copied instance and return it.

Secondly, why does an NSDictionary use a copy of the instance added to it rather than the instance itself?

Undistraction
  • 42,754
  • 56
  • 195
  • 331

2 Answers2

3

The subclass does not need to implement NSCopying if it is the object, the key should usually be NSStrings, which are copied.

hypercrypt
  • 15,389
  • 6
  • 48
  • 59
  • Right: Only keys need to implement `NSCopying`. – Wevah Sep 26 '11 at 14:54
  • Sorry I was unclear. The object will be used as a key. I've amended the question to reflect this. So why does it need a copy of the object rather than the object itself? – Undistraction Sep 26 '11 at 15:05
  • Also, if you need to have custom behaviour on your keys / objects, have a look at [CFDictionary](http://developer.apple.com/library/ios/#documentation/CoreFoundation/Reference/CFDictionaryRef/Reference/reference.html) and [CFMutableDictionary](http://developer.apple.com/library/ios/#documentation/CoreFoundation/Reference/CFMutableDictionaryRef/Reference/reference.html) which are toll-free bridged to `NSDictionary` and `NSMutableDictionary` – hypercrypt Sep 26 '11 at 15:13
  • 1
    Thanks for the links. Missed that first one somehow. Just found this as well which explains how to correctly implement an object for use as a key (and so you can use it for comparison) http://bynomial.com/blog/?p=73 – Undistraction Sep 26 '11 at 15:38
1
  1. You have to implement NSCopying protocol for every custom class if you want make them copyable
  2. It must use a copy because if you will modify an object contained in the original dictionary it's copy won't be affected by the change
daveoncode
  • 18,900
  • 15
  • 104
  • 159