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

前端 未结 27 3884
予麋鹿
予麋鹿 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 05:03

    I did this in iOS 4 using a block. Had to cast the elements of my array from id to my class type. In this case it was a class called Score with a property called points.

    Also you need to decide what to do if the elements of your array are not the right type, for this example I just returned NSOrderedSame, however in my code I though an exception.

    NSArray *sorted = [_scores sortedArrayUsingComparator:^(id obj1, id obj2){
        if ([obj1 isKindOfClass:[Score class]] && [obj2 isKindOfClass:[Score class]]) {
            Score *s1 = obj1;
            Score *s2 = 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;
    }];
    
    return sorted;
    

    PS: This is sorting in descending order.

提交回复
热议问题