【问题标题】:Trouble sorting custom objects in an NSArray numerically对 NSArray 中的自定义对象进行数字排序时遇到问题
【发布时间】:2015-05-15 07:55:41
【问题描述】:

如果我尝试按 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];
                                 }];

两者都返回错误的接收器类型。对整数或 NSInteger 进行比较有什么问题?

【问题讨论】:

  • 比较方法适用于 NSNumber 不适用于 int 或 NSInteger
  • ...所以任何合理的编译器设置,都不应该编译。

标签: ios objective-c arrays sorting nsarray


【解决方案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;
}

根据您的要求进行更改。

可以帮到你。

【讨论】:

  • 谢谢,这很有帮助。我现在意识到您无法跨整数进行比较。
  • 由于阻塞,我将其修改为使用“else”而不是“else if”。
  • @Macness ,你不应该这样做,最好使用更新的。
【解决方案2】:

更好的方法:

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

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

【讨论】:

  • 只是好奇,使用描述符比使用块更好吗?
  • 这样更好,因为您无需担心 playerScode 类型是 NSNumber、NSInteger、int 还是其他类型,也不需要您编写自己的比较器。
  • 它也慢了好几倍。而且灵活性差很多。
猜你喜欢
  • 1970-01-01
  • 2014-06-13
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-08-30
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多