如果我使用比较对对象进行排序,如何判断其中一个对象是否为零?

时间:2013-09-01 20:52:23

标签: ios objective-c sorting

说我有以下代码块:

[allKeys sortUsingComparator:^NSComparisonResult(id obj1, id obj2) {
    NSDictionary *firstArticle = [articles objectForKey:(NSString *)obj1];
    NSNumber *firstSortID = [firstArticle objectForKey:@"sort_id"];

    NSDictionary *secondArticle = [articles objectForKey:(NSString *)obj2];
    NSNumber *secondSortID = [secondArticle objectForKey:@"sort_id"];

    if (firstSortID == nil || secondSortID == nil) {
        return nil;
    }
    else {
        return [secondSortID compare:firstSortID];
    }
}];

我收到警告:

  

指向整数转换的指针不兼容从'返回'void *'   结果类型为'NSComparisonResult'的函数(又名'枚举'   NSComparisonResult')

但基本上,如果其中一个是零,它会崩溃,因为比较没有意义。如何判断它是否为零,请不要打扰,只需停下来。

2 个答案:

答案 0 :(得分:3)

您必须决定如何对nil值进行排序。他们很可能应该在列表的末尾。你想要这样的东西:

if (firstSortID) {
    if (secondSortID) {
        // Both set, compare
        NSComparisonResult result = [firstSortID compare:secondSortID];
        if (result == NSOrderedSame) {
            // optionally do another comparison on a secondary value
            // result = ...
        }
        return result;
    } else {
        // Have 1st but not 2nd
        return NSOrderedAscending;
    }
} else {
    if (secondSortID) {
       // Have 2nd but not 1st
       return NSOrderedDescending;
    } else {
       // Both nil, treat as the same
       // Another option here is to look at another value in the dictionary to be used as a secondary sort
       return NSOrderedSame;
    }
}

答案 1 :(得分:0)

您不能使用sortUsingComparator:提前终止排序。因此,您必须对nil值进行排序 - 只需确定nil是最小值还是最大值,然后根据需要返回NSOrderedDescendingNSOrderedAscendingNSOrderedSame。< / p>

如果您需要知道是否点击了nil,那么在您的区块中设置一个标记,您可以在之后进行测试。该标志需要使用__block限定符声明,以便可以在您的块中进行修改,例如:

__block BOOL nilFound = NO;
[allKeys sortUsingComparator:^NSComparisonResult(id obj1, id obj2)
{
   NSDictionary *firstArticle = [articles objectForKey:(NSString *)obj1];
   NSNumber *firstSortID = [firstArticle objectForKey:@"sort_id"];

   NSDictionary *secondArticle = [articles objectForKey:(NSString *)obj2];
   NSNumber *secondSortID = [secondArticle objectForKey:@"sort_id"];

   // set flag - could alternatively be set during comparison logic below
   if (firstSortID == nil || secondSortID == nil)
      nilFound = YES;

   // actual comparison, allowing for nil values
   ...
}];

// was a nil found?
if (nilFound) ...

<强>附录

其他人提出了稳定排序的问题,你应该能够通过使用原始密钥解决这个问题,例如:

if (firstSortID == nil)
{
   if (secondSortID == nil)
   {
      // both nil - use original keys as secondary sort, obj1 & obj2 are strings
      return [obj1 compare:obj2];
   }
   else
      return NSSortAscending;
}
else
   return secondSortID == nil ? NSSortDescending : [secondSortID compare:firstSortID];

(您可以切换NSSortAscending&amp; NSSortDescending,将nil值分组到另一端。)