无法以数字方式对 NSArray 中的自定义对象进行排序

Trouble sorting custom objects in an NSArray numerically

如果我尝试按 playerScore 属性:

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

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];
                                 }];

这两种 return 错误的接收器类型。对 int 或 NSInteger 进行比较有什么问题?

试试这个:

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;
}

根据您的要求更改。

可能对你有帮助。

更好的方法:

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

对于降序,将 YES 更改为 NO。