簡體   English   中英

如何在Objective-C的NSDictionary中切換兩個值?

[英]How to switch two values in an NSDictionary in 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;

我究竟做錯了什么?

除了幾個較大的問題(如果要更改內容,您應該使用NSMutableDictionary而不是NSDictionary ,並且應該使用setObject:forKey:方法而不是setValue:forKey:方法),問題的根源在於此線:

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

考慮一下您要設置的鍵。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM