Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using an int as an NSDictionary key?

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

like image 311
user339946 Avatar asked Feb 12 '12 22:02

user339946


People also ask

How do you set a value in NSDictionary?

You have to convert NSDictionary to NSMutableDictionary . You have to user NSMutableDictionary in place of the NSDictionary . After that you can able to change value in NSMutableDictionary . Save this answer.

How do I create an NSDictionary in Objective C?

Creating NSDictionary Objects Using Dictionary Literals In addition to the provided initializers, such as init(objects:forKeys:) , you can create an NSDictionary object using a dictionary literal. In Objective-C, the compiler generates code that makes an underlying call to the init(objects:forKeys:count:) method.

What is the difference between NSMapTable vs NSDictionary?

NSDictionary / NSMutableDictionary copies keys, and holds strong references to values. NSMapTable is mutable, without an immutable counterpart. NSMapTable can hold keys and values with weak references, in such a way that entries are removed when either the key or value is deallocated.

What is the difference between NSDictionary and NSMutableDictionary?

The key difference: NSMutableDictionary can be modified in place, NSDictionary cannot. This is true for all the other NSMutable* classes in Cocoa. NSMutableDictionary is a subclass of NSDictionary, so everything you can do with NSDictionary you can do with both.


2 Answers

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];
like image 53
Peter Kämpf Avatar answered Sep 24 '22 06:09

Peter Kämpf


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.

like image 39
bneely Avatar answered Sep 24 '22 06:09

bneely