Jem
Jem

Reputation: 6426

Using NSObjects as keys to a NSDictionary?

I have this BasicNode interface extending NSObject.

At some point, I need to use an instance of it as key to a dictionary:

BasicNode *node = [BasicNode node];
[aMutableDictionary setObject:@"hello" forKey:node]

This crashes the program,"signal SIGABRT". In Java, a hashmap would call a default hash method on the object to get its key. Is there a mechanism to implement in objC to allow using objects as keys to an NS(Mutbale)Dictionary?

Upvotes: 0

Views: 129

Answers (1)

Balazs Nemeth
Balazs Nemeth

Reputation: 2332

Yes, you can use an NSObject inheritance as Key, but it must implement the

 + (id)copyWithZone:(NSZone *)zone

method, and this is the requirement for using as a key. To implement it your own class is something like this:

 - (id)copyWithZone:(NSZone *)zone {
      MyObject *objectCopy = [[MyObject allocWithZone:zone] init];
      // Copy over all instance variables from self to objectCopy.
      // Use deep copies for all strong pointers, shallow copies for weak.
      return objectCopy;
 }

This is from this blog post!

Good luck!

Upvotes: 2

Related Questions