Created
September 4, 2011 21:58
-
-
Save mattyohe/1193584 to your computer and use it in GitHub Desktop.
Simple sorting of an array of dictionaries using the NSComparator block
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
NSMutableArray *mutArry = [[NSMutableArray alloc] init]; | |
// Fill array with 20 dictionaries that each contain a NSNumber for key "num" | |
for(int i = 0;i<20;i++){ | |
NSDictionary *dict = [[NSDictionary alloc] initWithObjectsAndKeys:[NSNumber numberWithInt:arc4random()%100], @"num", nil]; | |
[mutArry addObject:dict]; | |
} | |
// Print out unsorted array | |
NSLog(@"Unsorted array of dictionaries\n"); | |
for(NSDictionary *dict in mutArry){ | |
int i = [[dict objectForKey:@"num"] intValue]; | |
NSLog(@"%d\n",i); | |
} | |
// Use NSComparator block to return a sorted array | |
NSArray *sorted = [mutArry sortedArrayUsingComparator:^NSComparisonResult(id obj1, id obj2) { | |
int num1 = [[obj1 objectForKey:@"num"] intValue]; | |
int num2 = [[obj2 objectForKey:@"num"] intValue]; | |
if(num1<num2) return NSOrderedAscending; | |
if(num1>num2) return NSOrderedDescending; | |
return NSOrderedSame; | |
}]; | |
// Print out sorted array | |
NSLog(@"\nSorted array of dictionaries\n"); | |
for(NSDictionary *dict in sorted){ | |
int i = [[dict objectForKey:@"num"] intValue]; | |
NSLog(@"%d\n",i); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment