Skip to content

Instantly share code, notes, and snippets.

@chisj
Created October 23, 2012 01:50
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 chisj/3936202 to your computer and use it in GitHub Desktop.
Save chisj/3936202 to your computer and use it in GitHub Desktop.
Object-C Sort Array of Dictionary
void sortArrayOfDictionary {
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];
NSLog(@"before sort the arr is:%@", arr);
NSArray *sortedArray = [arr sortedArrayUsingComparator: ^(id obj1, id obj2) {
if ( ([[obj1 objectForKey:@"a"] intValue] < [[obj2 objectForKey:@"a"] intValue]) || ([[obj1 objectForKey:@"a"] intValue] == [[obj2 objectForKey:@"a"] intValue] && [[obj1 objectForKey:@"b"] intValue] > [[obj2 objectForKey:@"b"] intValue] ) ) {
return (NSComparisonResult)NSOrderedDescending ;
} else {
return (NSComparisonResult)NSOrderedAscending;
}
}];
NSLog(@"after sort the arr is:%@", sortedArray);
return;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment