无法在数字上对NSArray中的自定义对象进行排序

时间:2015-05-15 07:55:42

标签: ios objective-c arrays sorting nsarray

如果我尝试按BL_Player属性对playerScore进行排序:

NSArray *sortedPlayers = [players sortedArrayUsingComparator: ^(BL_Player *a1, BL_Player *a2) {
                                 return [a1.playerScore compare:a2.playerScore options:NSNumericSearch];

OR

NSArray *sortedPlayers = [players sortedArrayUsingComparator:^NSComparisonResult(id a, id b) {
                                     NSInteger first = [(BL_Player *)a playerScore];
                                     NSInteger second = [(BL_Player *)b playerScore];
                                     return [first compare:second options:NSNumericSearch];
                                 }];

两者都返回不良接收器类型。对int或NSInteger进行比较有什么问题?

2 个答案:

答案 0 :(得分:1)

试试这个:

NSArray *sortedPlayers = [players sortedArrayUsingComparator: ^(BL_Player *a1, BL_Player *a2) {

    if (a1.playerScore > a2.playerScore) {
        return NSOrderedAscending;
    } 
    else if (a1.playerScore < a2.playerScore) {
        return NSOrderedDescending;
    }
    else
       return NSOrderedSame;
}

根据您的要求进行更改。

可以帮助你。

答案 1 :(得分:0)

更好的方法:

NSSortDescriptor *sortDescriptor;
sortDescriptor = [[NSSortDescriptor alloc] initWithKey:@"playerScore"
                                              ascending:YES];
NSArray *sortDescriptors = [NSArray arrayWithObject:sortDescriptor];
NSArray *sortedArray;
sortedArray = [players sortedArrayUsingDescriptors:sortDescriptors];

降序将YES更改为NO。