Undistraction
Undistraction

Reputation: 43401

NSCopying, copyWithZone and NSDictionary

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?

Upvotes: 1

Views: 2730

Answers (2)

daveoncode
daveoncode

Reputation: 19618

  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

Upvotes: 1

hypercrypt
hypercrypt

Reputation: 15376

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

Upvotes: 3

Related Questions