ios - Obj-C - 如何保护此排序数组免受空值影响

标签 ios objective-c arrays

我有一些要排序的 Json 输入数组。某些排序描述符可能具有空值。如何防止空值异常?谢谢。

我目前拥有的是:

//sort the group arrays
    NSSortDescriptor *sortDescriptor1a;
    NSSortDescriptor *sortDescriptor1b;
    sortDescriptor1a = [[NSSortDescriptor alloc] initWithKey:@"Min" ascending:YES selector:@selector(caseInsensitiveCompare:)];
    sortDescriptor1b = [[NSSortDescriptor alloc] initWithKey:@"Line" ascending:YES selector:@selector(caseInsensitiveCompare:)];
    NSArray *sortDescriptors1 = [NSArray arrayWithObjects:sortDescriptor1a, sortDescriptor1b, nil];
    NSArray *tempArray1 = [unsortedGroup1 sortedArrayUsingDescriptors:sortDescriptors1 ];
    currentGroup1 = [tempArray1 mutableCopy];

    NSSortDescriptor *sortDescriptor2a;
.....

最佳答案

nil 值的情况下,您希望的排序行为是什么?以下将把 nil 值推到数组的末尾。

NSArray *sortedGroup1 = [unsortedGroup1 sortedArrayUsingComparator:^NSComparisonResult(id obj1, id obj2) {
  NSComparisonResult result = NSOrderedSame;
  if (obj1.Min && obj2.Min) {
    result = [obj1.Min caseInsensitiveCompare:obj2.Min];
  } else if (obj1.Min) {
    result = NSOrderedDescending;
  } else if (obj2.Min) {
    result = NSOrderedAscending;
  }

  if (result == NSOrderedSame) {
    if (obj1.Line && obj2.Line) {
      result = [obj1.Line caseInsensitiveCompare:obj2.Line];
    } else if (obj1.Line) {
      result = NSOrderedDescending;
    } else if (obj2.Line) {
      result = NSOrderedAscending;
    }
  } 
  return result;
}];

关于ios - Obj-C - 如何保护此排序数组免受空值影响,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28812793/

相关文章:

ios - 双击 UITableView

arrays - 存储类的结构数组

arrays - 将对象推送到 mongoDB 中的数组

ios - 什么是 Core Audio 错误 561015905,为什么在我使用锁定按钮时会发生?

ios - 为什么 UITableView cell separatorInset 默认为 15,而 View Controller 的 Root View Layout Margins 是 16?

objective-c - Objective-C 选择器参数的 Swift 默认值

objective-c - 直接访问子类中自动合成的实例变量?

javascript - 为什么这个对象似乎在不应该被访问的时候被访问了?

iOS。 xcode 在文档目录/开始时复制一个零字节的 sqlite 数据库

使用 md5 key 的 iOS 3DES 加密