0

I'd like to create an NSMutableDictionary that's keyed on a particular object and maps to an NSNumber. The object comes from a 3rd-party library and doesn't implement the copyWithZone method. The compiler understandably complains about the unrecognized selector (copyWithZone) being sent to the object, using the code:

[dictionary setObject:[NSNumber numberWithInt:index] forKey:someObject];

Since I didn't want to create my own copyWithZone method for a 3rd-party library object which I shouldn't need to know how to copy, I stayed away from creating a category that implements the method.

My hack was to store the memory address in an NSNumber by converting it to a long long:

[dictionary setObject:[NSNumber numberWithInt:index] forKey:[NSNumber numberWithLongLong:(long long)someObject]];

To retrieve the value:

NSNumber *indexNumber = [dictionary objectForKey:[NSNumber numberWithLongLong:(long long)someObject]];

This seems very hackish to me. What would be a cleaner way to handle the object-to-int mapping?

rimsky
  • 1,163
  • 3
  • 16
  • 27

1 Answers1

0

Just use associated objects...

See How do I use objc_setAssociatedObject/objc_getAssociatedObject inside an object?

That q/a has a good example.

(Associated objects allow you to associate an arbitrary set of objects with another object, using a key to look up any individual object.)

Community
  • 1
  • 1
bbum
  • 162,346
  • 23
  • 271
  • 359