如何在Objective-C中切换NSDictionary中的两个值?
我有一个带有两个值的如何在Objective-C中切换NSDictionary中的两个值?,objective-c,xcode,cocoa-touch,Objective C,Xcode,Cocoa Touch,我有一个带有两个值的NSDictionary。现在我想切换这些值。这是我的密码: NSDictionary *aDictionary = [[NSDictionary alloc] init]; [aDictionary setValue:@"theValue1" forKey:@"theKey1"]; [aDictionary setValue:@"theValue2" forKey:@"theKey2"]; NSString *tmpValue = [aDictionary objectF
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;
我做错了什么?除了几个更大的问题(如果要更改内容,应该使用
NSMutableDictionary
而不是NSDictionary
,并且应该使用setObject:forKey:
方法而不是setValue:forKey:
方法),问题的根源是这一行:
[aDictionary setValue:tmpValue forKey:[myDict objectForKey:@"theKey2"]];
想想你在设置什么键。明白了,伙计。非常感谢。我一定是盯着屏幕看太久了