How do I sort an NSMutableArray with custom objects in it?

前端 未结 27 3361
予麋鹿
予麋鹿 2020-11-21 04:45

What I want to do seems pretty simple, but I can\'t find any answers on the web. I have an NSMutableArray of objects, and let\'s say they are \'Person\' objects

27条回答
  •  我寻月下人不归
    2020-11-21 04:59

    Compare method

    Either you implement a compare-method for your object:

    - (NSComparisonResult)compare:(Person *)otherObject {
        return [self.birthDate compare:otherObject.birthDate];
    }
    
    NSArray *sortedArray = [drinkDetails sortedArrayUsingSelector:@selector(compare:)];
    

    NSSortDescriptor (better)

    or usually even better:

    NSSortDescriptor *sortDescriptor;
    sortDescriptor = [[NSSortDescriptor alloc] initWithKey:@"birthDate"
                                               ascending:YES];
    NSArray *sortedArray = [drinkDetails sortedArrayUsingDescriptors:@[sortDescriptor]];
    

    You can easily sort by multiple keys by adding more than one to the array. Using custom comparator-methods is possible as well. Have a look at the documentation.

    Blocks (shiny!)

    There's also the possibility of sorting with a block since Mac OS X 10.6 and iOS 4:

    NSArray *sortedArray;
    sortedArray = [drinkDetails sortedArrayUsingComparator:^NSComparisonResult(id a, id b) {
        NSDate *first = [(Person*)a birthDate];
        NSDate *second = [(Person*)b birthDate];
        return [first compare:second];
    }];
    

    Performance

    The -compare: and block-based methods will be quite a bit faster, in general, than using NSSortDescriptor as the latter relies on KVC. The primary advantage of the NSSortDescriptor method is that it provides a way to define your sort order using data, rather than code, which makes it easy to e.g. set things up so users can sort an NSTableView by clicking on the header row.

提交回复
热议问题