我有一個從請求返回的JSON數組。
數據作爲這樣的(它來自外部源,並且不能從服務器改變):在JSON中NSDictionary/NSArray中正確保存KEYS
[{"clients":
{"name":"Client name here","telephone":"00000","email":"[email protected]","website":"www.clientname.com"}
}]
我接收JSON數組的順序。
我有以下的Objective-C:
//jsonString is the json string inside type NSString.
NSMutableDictionary *tempDict = [jsonString JSONValue];
NSMutableDictionary *clients = [tempDict objectForKey:@"clients"];
for(NSString *key in clients) {
id value = [tempDict objectForKey:key];
for(NSString *itemKey in key) {
NSLog(@"ITEM KEY %@: ",itemKey);
}
}
它打印按鍵的順序是:
電話
電子郵件
名
網站
我需要它來打印如何它被接收(例如):
名稱
電話
電子郵件
網站
我讀過字典根據定義未排序,所以很高興使用數組而不是字典。
但我已經(使用keysSortedByValueUsingSelector
)看到在計算器上就可能解決多個線程:
Getting NSDictionary keys sorted by their respective values
Can i sort the NSDictionary on basis of key in Objective-C?
sort NSDictionary keys by dictionary value into an NSArray
Can i sort the NSDictionary on basis of key in Objective-C?
我曾嘗試他們和我越來越行不通。不知道這是否只是我的實現是錯誤的。
我試圖(嘗試1):
NSArray *orderedKeys = [clients keySortedByValueUsingComparator:^NSComparisonResult(id obj1, id obj2){
return [obj1 compare:obj2];
}];
for(NSString *key in orderedKeys) {
id value = [tempDict objectForKey:key];
for(NSString *keyThree in key) {
NSLog(@"API-KEY-ORDER %@: ",keyThree);
}
}
接收錯誤:[__NSArrayM keySortedByValueUsingComparator:]: unrecognized selector sent to instance
。
還試圖(嘗試2):
NSArray *sortedKeys = [[clients allKeys] sortedArrayUsingSelector: @selector(compare:)];
NSMutableArray *sortedValues = [NSMutableArray array];
for (NSString *key in sortedKeys){
[sortedValues addObject: [tempDict objectForKey: key]];
//[sortedValues addObject: [all objectForKey: key]]; //failed
}
但在選擇另一個錯誤,即使客戶是一個的NSMutableDictionary。
[__NSArrayM allKeys]: unrecognized selector sent to instance 0x4b6beb0
我在哪裏,我認爲我會遍歷NSMutableDictionary
,並手動將它們放入一個新NSMutableArray
以正確的順序點。
任何想法將非常感激?
OR anybodies code snippet attempt at my problem will equal to appreciate。
看起來好像'clients'是一個'NSArray',你試圖在它上面執行'NSDictionary'的選擇器 – 2013-04-11 15:42:34
是的,我不在乎它爲什麼這麼想。你可以在上面看到'clients'是一個'NSMutableDictionary'。 – 2013-04-11 15:44:12
在客戶端啓動後放置一個斷點,並在控制檯中輸入「po clients」。控制檯顯示什麼類? – 2013-04-11 15:48:23