ITeye博客

NSMutableArray 中排序

alex09 · 2011-07-24 14:02 · iphone开发 · 移动开发 · Markdown

使用sortedArrayUsingComparator方法

NSArray *sorted = [_scores sortedarrayusingcomparator:^(id obj1, id obj2){
    if ([obj1 iskindofclass:[score class]] && [obj2 iskindofclass:[score class]]) {
        Score *s1 = (Score*)obj1;
        Score *s2 = (Score*)obj2;

        if (s1.points > s2.points) {
            return (NSComparisonResult)NSOrderedAscending;
        } else if (s1.points < s2.points) {
            return (NSComparisonResult)NSOrderedDescending;
        }
    }

    // TODO: default is the same?
    return (NSComparisonResult)NSOrderedSame;
}];

使用sortedArrayUsingSelector方法

- (NSComparisonResult)compare:(Person *)otherObject {
    return [self.birthdate compare:otherobject.birthdate];
}

NSArray *sortedArray;
sortedArray = [drinkdetails sortedarrayusingselector:@selector(compare:)];

使用sortedArrayUsingDescriptors:sortDescriptors

NSSortDescriptor *sortDescriptor;
sortDescriptor = [[[nssortdescriptor alloc] initWithKey:@"birthDate"
                                              ascending:YES] autorelease];
NSArray *sortDescriptors = [nsarray arraywithobject:sortdescriptor];
NSArray *sortedArray;
sortedArray = [drinkdetails sortedarrayusingdescriptors:sortdescriptors];

评论(0)

暂无评论。

评论功能维护中,当前仅展示历史评论。