Sort NSDictionary

折月煮酒 提交于 2019-12-04 06:45:30

问题


I got NSDictionary with pairs like :

Key -> Value:
@"home" -> @"blue"
@"family" -> @"green"
@"work" -> @"red"

Updated

Internet said no one can sort NSDictionary :c

This code helped me with values.

sortedArray = [anArray sortedArrayUsingSelector:@selector(localizedCaseInsensitiveCompare:)];

But i lose relation between keys and values. If anybody can write function, which take NSDictionary and make two NSArray, which related and one of those arrays sorted by values of NSDictionary like this:

(unsorted)
    Key -> Value:
    @"work" -> @"red"
    @"home" -> @"blue"
    @"family" -> @"green"

convert to:

Arrays, which keep relationship by index of item and one of them (values of NSDictionary) sorted

    ArrayOfKeys = {@"home",@"family",@"work"}
    ArrayOfValues = {@"blue", @"green", @"red"} -- this one sorted like alphabet

回答1:


You can access the keys in a sorted order with method like keysSortedByValueUsingComparator, keysSortedByValueWithOptions or keysSortedByValueUsingSelector. But by definition a NSDictionary itself has no notion or order.




回答2:


You can't sort an NSDictionary. If you want , you could create an object to hold the key and value in it, then add to an array and use a sort descriptor to sort on the key field.




回答3:


NSDictionary is not an ordered collection, however you can sort its keys using comparators like keysSortedByValueUsingComparator, keysSortedByValueUsingSelector.



来源:https://stackoverflow.com/questions/19344737/sort-nsdictionary

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!