Skip to content

Instantly share code, notes, and snippets.

@ylem
Created October 29, 2012 22:11
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ylem/3976878 to your computer and use it in GitHub Desktop.
Save ylem/3976878 to your computer and use it in GitHub Desktop.
sort dictionaries by key's value in an array
#import <Foundation/Foundation.h>
int main(int argc, const char * argv[])
{
@autoreleasepool {
// insert code here...
NSLog(@"Hello, World!");
NSArray *arr = [NSArray arrayWithObjects:
[NSDictionary dictionaryWithObjectsAndKeys:[NSNumber numberWithInt:5], @"a", [NSNumber numberWithInt:5], @"b",nil],
[NSDictionary dictionaryWithObjectsAndKeys:[NSNumber numberWithInt:6], @"a", [NSNumber numberWithInt:2], @"b",nil],
[NSDictionary dictionaryWithObjectsAndKeys:[NSNumber numberWithInt:2], @"a", [NSNumber numberWithInt:7], @"b",nil],
[NSDictionary dictionaryWithObjectsAndKeys:[NSNumber numberWithInt:5], @"a", [NSNumber numberWithInt:2], @"b",nil],
[NSDictionary dictionaryWithObjectsAndKeys:[NSNumber numberWithInt:1], @"a", [NSNumber numberWithInt:0], @"b",nil],
[NSDictionary dictionaryWithObjectsAndKeys:[NSNumber numberWithInt:5], @"a", [NSNumber numberWithInt:1], @"b",nil],
[NSDictionary dictionaryWithObjectsAndKeys:[NSNumber numberWithInt:6], @"a", [NSNumber numberWithInt:1], @"b",nil],
[NSDictionary dictionaryWithObjectsAndKeys:[NSNumber numberWithInt:2], @"a", [NSNumber numberWithInt:9], @"b",nil],
nil];
NSSortDescriptor *aDescriptor = [[NSSortDescriptor alloc] initWithKey:@"a" ascending:NO];
NSSortDescriptor *bDateDescriptor = [[NSSortDescriptor alloc] initWithKey:@"b" ascending:YES];
NSArray *sortDescriptors = @[aDescriptor, bDateDescriptor];
NSArray *sortedArray = [arr sortedArrayUsingDescriptors:sortDescriptors];
NSLog(@"after sort the arr is:%@", sortedArray);
}
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment