2011-07-25 91 views
1

我有一個NSDictionary數組。NSdictionary排序問題

NSDictionary* dictionary = [NSDictionary dictionaryWithObjects:bothUserName forKeys:bothUID]; // here array "bothUserName" and "bothUID" is an NSArray type 


[dictionary keysSortedByValueUsingSelector:@selector(compare:)]; 

NSLog(@" dictionary objects %@",dictionary); 

我得到這樣的輸出。

dictionary objects { 

14172368 = webtickle; 
271882407 = electrodealio; 
314125883 = Coral5mz; 
316212228 = ajaysinghHF2; 
316348693 = Caroline99a; 
43944597 = WorldStuffer; 
} 

但我想要這樣的輸出。

字典對象{

316212228 = ajaysinghHF2; 
316348693 = Caroline99a; 
314125883 = Coral5mz; 
271882407 = electrodealio; 
14172368 = webtickle; 
43944597 = WorldStuffer; 
} 

預先感謝。

+0

我想交換密鑰和值可能工作 – sujith1406

+0

@Ajay_Kumar出現了這個錯誤我假定鍵取代了值,但與使用塊方法相比,daveoncode的答案是正確的並且更好。 –

+0

但你的答案是正確的。我只修改返回[obj1 localizedCaseInsensitiveCompare:obj2];而不是string1和string2,它運行良好。是的,這個答案似乎還可以,但不幸的是工作不好。 –

回答

3

keysSortedByValueUsingSelector返回一個包含字典的鍵排序後的數組,你必須使用這個返回數組對象的關聯對象:

NSDictionary* dictionary = [NSDictionary dictionaryWithObjects:bothUserName forKeys:bothUID]; 

NSArray *sortedKeys = [dictionary keysSortedByValueUsingSelector:@selector(compare:)]; 

for (NSString *key in sortedKeys) { 
    NSLog(@"%@: %@", key, [dictionary objectForKey:key]); 
} 
+0

它沒有完美排序。輸出是這樣的。 「Caroline99a」, 「Coral5mz」, 「WorldStuffer」, 「ajaysinghHF2」, 「electrodealio」, 「webtickle」。 –

+0

@Ajay_Kumar使用'localizedCaseInsensitiveCompare:'代替'compare:'。 –