Take the 2-minute tour ×

I have an NSDictionary with two values. Now I want to switch the values. Here is my code:

NSDictionary *aDictionary = [[NSDictionary alloc] init];
[aDictionary setValue:@"theValue1" forKey:@"theKey1"];
[aDictionary setValue:@"theValue2" forKey:@"theKey2"];

NSString *tmpValue = [aDictionary objectForKey:@"theKey1"];
[aDictionary setValue:[myDict objectForKey:@"theKey2"] forKey:@"theKey1"];
[aDictionary setValue:tmpValue forKey:[myDict objectForKey:@"theKey2"]];
NSLog(@"%@", myDict); 

theKey1 = theValue2;
theKey2 = theValue2;
theValue2 = theValue1;

What am I doing wrong?

share|improve this question
add comment

1 Answer

up vote 3 down vote accepted

Other than a couple of larger problems (you should be using NSMutableDictionary instead of NSDictionary if you want to change things, and you should use the setObject:forKey: method instead of the setValue:forKey: method), the root of your problem is this line:


Think about what key you're setting.

share|improve this answer
got it man. Thank you. I must have been staring at the screen for too long –  stackoverflow Jan 24 '12 at 3:53
add comment

Your Answer


