I'm trying to access my dictionary object. Here's my code:

int tag = object.tag;
CGPoint point = [[self.dict objectForKey:tag] CGPointValue];

The problem is objectForKey is supposed to take an Objective-C object, not an int. I tried wrapping tag into an NSNumber with [NSNumber numberWithInt:tag] and passing that into objectForKey: but it returns a null object.

Any ideas? Thanks

  • 3
    How did you put the objects into self.dict in the first place? – mattjgalloway Feb 12 '12 at 22:39
  • initWithObjectsAndKeys: [NSValue valueWithCGPoint:CGPointMake(1,2)], @"100", etc. Note that my dictionary is fine, I'm accessing it in other parts of my code with a for-in (for id key in self.dict) loop. However in this instance I don't want to use a loop. Thanks – user339946 Feb 12 '12 at 22:49

If you are using numbers as strings for dictionary keys, you should turn the int into a NSString or NSNumber to use it as a dictionary key. Here's how to do it for a string:

  NSString *key = [NSString stringWithFormat:@"%d", myInteger];

As @Hughes BR mentions in a comment, the requirement for the key object is that it must conform to the NSCopying protocol.

  • Hi, I manually set my object.tag to be 100, 101, etc. The dictionary keys are written as @"101". Note that I have accessed the dictionary successfully in other parts of my code, specifically when I used a for-in loop. My dictionary objects and keys are all there. – user339946 Feb 12 '12 at 22:46
  • 16
    You needn't use a string. An NSNumber would suffice and would potentially be a more natural fit. [NSNumber numberWithInteger:[object tag]] would do the trick. – Sedate Alien Feb 13 '12 at 0:14
  • 1
    @SedateAlien, That's generally correct, but it's worth pointing out that for key-value coding (e.g. storing in NSUserDefaults), the key of the NSDictionary must be an NSString. – Jonathan Ellis May 7 '14 at 21:52
  • 1
    According to the doc, it's any object that respond to nscopying protocol. so nsnumber is fine. dict[@(1)] will work – Hugues BR Sep 17 '14 at 21:17
  • 1
    @(myInteger) would be a cleaner choice though – Iulian Onofrei Oct 28 '14 at 15:02

I use NSNumbers without problems, but must avoid the usual setObject: forKey: or setValue: forKey: methods. That would create a warning.

No warning, however, is created (and the code works as intended) with

NSMutableDictionary *myDict = [[NSMutableDictionary alloc] init];
NSNumber *key = @1;
id *myObject  = [your code here];
myDict[key]   = myObject;

Retrieval is straightforward:

myObject = myDict[key];

Your Answer

