Skip to content

Instantly share code, notes, and snippets.

@mattyohe
Created September 4, 2011 21:58
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 mattyohe/1193584 to your computer and use it in GitHub Desktop.
Save mattyohe/1193584 to your computer and use it in GitHub Desktop.
Simple sorting of an array of dictionaries using the NSComparator block
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