Reputation: 717
I have NSMutableDictionary with Integers as Key and NSString as Values for example:
Key -- Value
1 -- B
2 -- C
3 -- A
Now i want to Sort NSMutableDictionary alphabetically using values. So i want my dictionary to be like : Key(3,1,2)->Value(A,B,C). How can i perform this?
Upvotes: 0
Views: 2890
Reputation: 10424
try this logic
NSMutableDictionary *dict = [NSMutableDictionary dictionaryWithObjectsAndKeys:@"B",@"B",@"A",@"A",@"C",@"C", nil];
NSMutableArray *sortedArray = [NSMutableArray arrayWithArray:[dict allKeys]];
[sortedArray sortUsingSelector:@selector(localizedCaseInsensitiveCompare:)];
for (NSString *key in sortedArray) {
NSLog(@"%@",[dict objectForKey:key]);
}
Upvotes: 2
Reputation: 5152
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;
}];
Upvotes: 3