Created
October 23, 2012 01:50
-
-
Save chisj/3936202 to your computer and use it in GitHub Desktop.
Object-C Sort Array of Dictionary
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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