How can integers (keys & values) be added and retrieved from a NSDictionary
How can I add key (an int) and value (an int)开发者_运维问答 pair to a NSDictionary object? and how can they be retrieved as int?
Thanks!
The dictionary key and value has to be a object reference (id
) so you can't use an integer as the key. You should instead wrap your integers in a NSNumber
:
[NSNumber numberWithInt:5]
You can then initialize your NSDictionary
using one of the initWithObjects
initializers. I chose the initWithObjectsAsKeys:
initializer which accepts key/values in a value, key, value, key.. nil format.
NSDictionary *dict = [[NSDictionary alloc]initWithObjectsAndKeys:[NSNumber numberWithInt:15], [NSNumber numberWithInt:5], nil];
To access the value, you need to do the same:
NSLog(@"%@", [dict objectForKey:[NSNumber numberWithInt:5]]);
EDIT: According to your comment, it seems you should be using a NSMutableDictionary, not a NSDictionary. The same thing applies to wrapping your integers, but you'll want to use the setObject:forKey method:
NSMutableDictionary *dict = [[NSMutableDictionary alloc]init];
[dict setObject:[NSNumber numberWithInt:15] forKey:[NSNumber numberWithInt:5]];
Does that help?
Wrap it in an NSNumber
:
int intKey = 1;
int intValue = 2;
[myDict setObject:[NSNumber numberWithInt:intValue] forKey:[NSNumber numberWithInt:intKey]];
NSLog(@"key: %i, value: %i", intKey, [[myDict objectForKey:[NSNumber numberWithInt:intKey] intValue]);
EDIT: You need to use an NSMutableDictionary
to set values. NSDictionary
can't be modified after it's created.
精彩评论