问题
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