views:

686

answers:

3

In my app, I have a NSDictionary whose keys should be instances of a subclass of NSManagedObject.

The problem, however, is that NSManagedObject does not implement the NSCopying protocol which means that no Core Data objects / instances of NSManagedObject can be used as dictionary keys even though the -[hash] method works fine for them.

Was should I do?

A: 

Could you create a wrapper class, that contains a reference to the instance of NSManagedObject that you want to use as a dictionary key? You could then make this wrapper class implement NSCopying, along with a hash method (perhaps just calling the NSManagedObject's hash method), and use this wrapper as the dictionary key.

Tom
A: 

I suggest to use [[[myManagedObject objectID] URIRepresentation] absoluteString] as your key.

tlindner
There's no point to all this. NSManagedObjectID can be used fine as-is as it implements NSCopying.
Mike Abdullah
There is -- you can archive the URIRepresentation of the object ID (via NSCoding). Very useful if you want to copy an NSManagedObject into the pasteboard.
adib
+9  A: 

You have two options:

  1. Stick the object ID into a dictionary instead and work with that. NSManagedObjectID is NSCopying-compliant so will properly handle this
  2. NSDictionary's implementation boils down roughly to this internally:

    - (void)setObject:(id)anObject forKey:(id)aKey
    {
      id copiedKey = [aKey copy];
      CFDictionarySetValue(self, copiedKey, anObject);
      [copiedKey release];
    }

So you can just use CFDictionarySetValue() directly if you like.

Mike Abdullah