Sort an NSMutableDictionary
Get the Array of the Values, sort that array and then get the key corresponding to the value.
You can get the values with:
NSArray* values = [myDict allValues];
NSArray* sortedValues = [values sortedArrayUsingSelector:@selector(comparator)];
But, if the collection is as you show in your example, (I mean, you can infer the value from the key), you can always sort the keys instead messing with the values.
Using:
NSArray* sortedKeys = [myDict keysSortedByValueUsingSelector:@selector(comparator)];
The comparator is a message selector which is sent to the object you want to order.
If you want to order strings, then you should use a NSString comparator.
The NSString comparators are i.e.: caseInsensitiveCompare or localizedCaseInsensitiveCompare:.
If none of these are valid for you, you can call your own comparator function
[values sortedArrayUsingFunction:comparatorFunction context:nil]
Being comparatorFunction (from AppleDocumentation)
NSInteger intSort(id num1, id num2, void *context)
{
int v1 = [num1 intValue];
int v2 = [num2 intValue];
if (v1 < v2)
return NSOrderedAscending;
else if (v1 > v2)
return NSOrderedDescending;
else
return NSOrderedSame;
}
Sort values of NSMutableDictionary alphabetically
From Apple docs:
https://developer.apple.com/library/mac/documentation/Cocoa/Conceptual/Collections/Articles/Dictionaries.html#//apple_ref/doc/uid/20000134-SW4
Sorting dictionary keys by value:
NSDictionary *dict = [NSDictionary dictionaryWithObjectsAndKeys:
[NSNumber numberWithInt:63], @"Mathematics",
[NSNumber numberWithInt:72], @"English",
[NSNumber numberWithInt:55], @"History",
[NSNumber numberWithInt:49], @"Geography",
nil];
NSArray *sortedKeysArray =
[dict keysSortedByValueUsingSelector:@selector(compare:)];
// sortedKeysArray contains: Geography, History, Mathematics, English
Blocks ease custom sorting of dictionaries:
NSArray *blockSortedKeys = [dict keysSortedByValueUsingComparator: ^(id obj1, id obj2) {
if ([obj1 integerValue] > [obj2 integerValue]) {
return (NSComparisonResult)NSOrderedDescending;
}
if ([obj1 integerValue] < [obj2 integerValue]) {
return (NSComparisonResult)NSOrderedAscending;
}
return (NSComparisonResult)NSOrderedSame;
}];
how can I sort NSMutableDictionary with keys value?
A dictionary is unsorted by definition.
For iterating over the keys in a specific order, you can sort an array containing the keys of the dictionary.
NSArray *keys = [theDictionary allKeys];
NSArray *sortedKeys = [keys sortedArrayUsingSelector:@selector(compareMethod:)];
There are several other sorted...
methods, e.g. sorting with a NSComparator
. Have a look here.
Sort NSDictionary in ascending order
You can use NSSortDescriptor like this:
NSArray* array1 = @[@"1 = off", @"10 = off", @"2 = on", @"3 = on"];
NSSortDescriptor *descriptor = [NSSortDescriptor sortDescriptorWithKey:@"" ascending:YES selector:@selector(localizedStandardCompare:)];
NSLog(@"Ordered array: %@", [array1 sortedArrayUsingDescriptors:@[ descriptor ]]);
which produces this output:
2013-06-04 12:26:22.039 EcoverdFira[3693:c07] Ordered array: (
"1 = off",
"2 = on",
"3 = on",
"10 = off"
)
There's a good article on NSSortedDescriptor
's here.
How to Sort NSMutableDictionary in iOS
I tried below coding.it works fine for me
NSMutableDictionary *item = [[NSMutableDictionary alloc] init];
[item setValue:[NSString stringWithFormat: itemName] forKey:@"Title"];
[item setValue: [NSNumber numberWithInteger: itemCount] forKey:@"Count"];
[item setValue: [NSNumber numberWithFloat: itemScore] forKey:@"Score"];
[top3_Question_Array addObject:item];
NSSortDescriptor *countDescriptor = [[NSSortDescriptor alloc] initWithKey:@"Count" ascending:NO];
NSArray *descriptors = [NSArray arrayWithObjects:countDescriptor, nil];
NSArray *sortedArrayOfDictionaries = [top3_Question_Array sortedArrayUsingDescriptors:descriptors];
NSLog(@"sorted array of dictionaries: %@", sortedArrayOfDictionaries);
Also the expected output is
sorted array of dictionaries: (
{
Count = 2;
Score = 30;
Title = Cholate;
}
)
Swift Sort NSDictionary of NSDictionary by Value
Since a Dictionary
is inherently unsorted, you'll need to use an Array
instead. Fortunately, this is easily done via functional techniques:
guard let dict = nsDict as? [String : [String : String]] else { /* handle the error */ }
let sorted = dict.sorted { ($0.value["Name"] ?? "") < ($1.value["Name"] ?? "") }
print(sorted)
This will get you an Array
of tuples containing the keys and values of the respective dictionaries, sorted by "Name"
:
[(key: "KrqpSvSX7eKqYfvu5ZO", value: ["Name": "A", "Value": "", "Description": ""]),
(key: "Krqq2AWOqWKys0siTmc", value: ["Name": "B", "Value": "", "Description": ""])]
Alternately, you can simply get a sorted array of the String
keys:
let sortedKeys = dict.sorted { ($0.value["Name"] ?? "") < ($1.value["Name"] ?? "") }.map {
$0.key
}
print(sortedKeys)
which outputs:
["KrqpSvSX7eKqYfvu5ZO", "Krqq2AWOqWKys0siTmc"]
This array of keys can later be used to dynamically look up objects from the dictionary at runtime when populating the collection view. This method will be likely to be more expensive performance-wise than the first approach due to all the dictionary lookups, but will result in lower memory usage if you also need to keep the original dictionary around in its original form for some reason.
Related Topics
How to Rotate Text for Uibutton and Uilabel in Objective-C
Swift Equivalent to '[Nsdictionary Initwithobjects: Forkeys:]'
Renew Push Certificate and Keep Current App Store App Working
Attempt to Insert Non-Property List Object When Trying to Save a Custom Object in Swift 3
How to Reset the Privacy Settings in iOS
Uitableview: How to Disable Selection for Some Rows But Not Others
How to Load a Xib File in a Uiview
How to Show a Custom Uimenuitem for a Uitableviewcell
Save Data to .Plist File in Swift
Setneedslayout VS. Setneedsupdateconstraints and Layoutifneeded VS Updateconstraintsifneeded
iOS 8 Sdk: Modal Uiwebview and Camera/Image Picker
Foreign Key Relationship Mapping with Restkit
Swift Programmatically Navigate to Another View Controller/Scene
Invalid Swift Support/Invalid Implementation of Swift
How to Opt Your iPad App Out of Multitasking on iOS 9