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);
//output
theKey1 = theValue2;
theKey2 = theValue2;
theValue2 = theValue1;
What am I doing wrong?
Other than a couple of larger problems (you should be using
NSMutableDictionaryinstead ofNSDictionaryif you want to change things, and you should use thesetObject:forKey:method instead of thesetValue:forKey:method), the root of your problem is this line:Think about what key you’re setting.