Skip to content

Instantly share code, notes, and snippets.

@ericmulder
Created October 16, 2012 06:19

Revisions

  1. ericmulder revised this gist Oct 16, 2012. 1 changed file with 1 addition and 1 deletion.
    2 changes: 1 addition & 1 deletion gistfile1.m
    Original file line number Diff line number Diff line change
    @@ -28,7 +28,7 @@
    return (NSComparisonResult)NSOrderedSame;
    }

    //chapter 1 = bigger
    //chapter 1 = smaller
    if (obj1Chapter < obj2Chapter) {
    return (NSComparisonResult)NSOrderedAscending;
    }
  2. ericmulder revised this gist Oct 16, 2012. 1 changed file with 33 additions and 1 deletion.
    34 changes: 33 additions & 1 deletion gistfile1.m
    Original file line number Diff line number Diff line change
    @@ -2,4 +2,36 @@

    //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];
    [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 = bigger
    if (obj1Chapter < obj2Chapter) {
    return (NSComparisonResult)NSOrderedAscending;
    }

    return (NSComparisonResult)NSOrderedSame;
    }];
  3. ericmulder created this gist Oct 16, 2012.
    5 changes: 5 additions & 0 deletions gistfile1.m
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,5 @@
    //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];