Thunder Rabbit
Thunder Rabbit

Reputation: 5449

how can I call objectForKey from an NSDictionary with an int where the keys are NSNumbers

I'm trying to get and set from an NSDictionary with NSNumbers as the keys. I think I'm doing things according to this answer https://stackoverflow.com/a/6891489/194309 but my code below returns null values.

- (void)viewDidLoad {
    [super viewDidLoad];

    NSInteger const SET1 = 1;
    NSInteger const SET2 = 2;


    videoKeyOfTag = [[NSDictionary alloc] initWithObjectsAndKeys:
                    [NSNumber numberWithInt:SET1], @"well",
                    [NSNumber numberWithInt:SET2], @"great",
                    nil];
    NSLog(@"to see well: %@",[videoKeyOfTag objectForKey:[NSNumber numberWithInt:SET1]]);   

}

I expect to see well: well in the log but instead I see what I don't want:

to see well: (null)

Starting with an int, how can I call objectForKey from an NSDictionary where the keys are NSNumbers?

(I eventually want to extract values from the NSDictionary with [sender tag] as the meta-key.)

Upvotes: 0

Views: 1342

Answers (3)

user529758
user529758

Reputation:

There's a reason the initializer method is called initWithObjectsAndKeys: and not initWithKeysAndObjects: (although the latter would make more sense for me, but this is Apple...) Anyway, the odd-number arguments (1st, 3rd, etc) are the values, the even-numbered (2nd, 4th, etc) are the keys. So try:

videoKeyOfTag = [[NSDictionary alloc] initWithObjectsAndKeys:
                @"well", [NSNumber numberWithInt:SET1],
                @"great", [NSNumber numberWithInt:SET2],
                nil];

instead.

Upvotes: 1

taskinoor
taskinoor

Reputation: 46037

initWithObjectsAndKeys - here first argument is value, second one is key. You are doing the opposite. You have used @"well" and @"great" as keys, not values. You should write:

videoKeyOfTag = [[NSDictionary alloc] initWithObjectsAndKeys:
                    @"well", [NSNumber numberWithInt:SET1],
                    @"great", [NSNumber numberWithInt:SET2],
                    nil];

Upvotes: 1

Monolo
Monolo

Reputation: 18253

If you want the numbers to be keys, you need to invert the order in the constructor:

videoKeyOfTag = [[NSDictionary alloc] initWithObjectsAndKeys:
                    @"well", [NSNumber numberWithInt:SET1], 
                    @"great", [NSNumber numberWithInt:SET2], 
                    nil];

Upvotes: 1

Related Questions