2012-01-24 45 views
1

我有一個NSDictionary有兩個值。現在我想切換這些值。這裏是我的代碼:如何在Objective-C的NSDictionary中切換兩個值?

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; 

我在做什麼錯?

回答

3

除了幾個大的問題(你應該使用NSMutableDictionary代替NSDictionary,如果你想改變的東西,你應該使用setObject:forKey:方法,而不是setValue:forKey:方法),你的問題的根源在於這一行:

[aDictionary setValue:tmpValue forKey:[myDict objectForKey:@"theKey2"]]; 

想想你正在設置什麼鍵。

+0

明白了吧。謝謝。我一定是盯着屏幕太久了 – stackoverflow

相關問題