Skip to content

Instantly share code, notes, and snippets.

@ericmulder
Created October 16, 2012 06:19
Show Gist options
  • Save ericmulder/3897504 to your computer and use it in GitHub Desktop.
Save ericmulder/3897504 to your computer and use it in GitHub Desktop.
NSSortDescriptor
//How to sort the following list?
//Array with NSStrings:
[NSArray arrayWithObjects:@"0.0 Title", @"1.1 Title", @"1.10 Title", @"1.11 Title", @"1.12 Title", @"1.2 Title", @"10.1 Title",@"10.11 Title",@"10.2 Title",@"2.1 Title", nil];
Solution:
NSSortDescriptor *sortDescriptor;
sortDescriptor = [NSSortDescriptor sortDescriptorWithKey:@"title" ascending:YES comparator:^NSComparisonResult(id obj1, id obj2) {
NSArray *obj1Array = [obj1 componentsSeparatedByString:@"."];
int obj1Chapter = [[obj1Array objectAtIndex:0] intValue];
int obj1SubChapter = [[obj1Array objectAtIndex:1] intValue];
NSArray *obj2Array = [obj2 componentsSeparatedByString:@"."];
int obj2Chapter = [[obj2Array objectAtIndex:0] intValue];
int obj2SubChapter = [[obj2Array objectAtIndex:1] intValue];
//chapter 1 = bigger
if (obj1Chapter > obj2Chapter) {
return (NSComparisonResult)NSOrderedDescending;
}
//chapter 1 == chapter 2
if (obj1Chapter == obj2Chapter) {
if(obj1SubChapter > obj2SubChapter) return (NSComparisonResult)NSOrderedDescending;
if(obj1SubChapter < obj2SubChapter) return (NSComparisonResult)NSOrderedAscending;
return (NSComparisonResult)NSOrderedSame;
}
//chapter 1 = smaller
if (obj1Chapter < obj2Chapter) {
return (NSComparisonResult)NSOrderedAscending;
}
return (NSComparisonResult)NSOrderedSame;
}];
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment