2013-04-02 58 views
0

编辑: 正如我想的那样,甚至没有问题,我只是使用错误的值来检查我的结果。无法使用自定义比较器对两个属性进行排序

我比较我的数据库的自定义对象和排序它们的目标有点麻烦,原则上,这很容易,排序机制必须与这个自定义对象的两个属性由字符串表示,但也可以包含数值。

这是我正在尝试修复的自定义比较器块。

NSArray *sortedArray = [baseAry sortedArrayUsingComparator:^NSComparisonResult(Obj *o1, Obj *o2) { 
NSComparisonResult comp1 = [o1.attr_a compare:o2.attr_a]; 
if (comp1 == NSOrderedSame) { 
    return [o1.attr_b compare:o2.attr_b];  
} 
return [o1.attr_a compare:o2.attr_a]; 
}]; 

最后,列表应该是这样的:

  • 12 - 3
  • 12 - 8
  • 13 - 1
  • 14 - 2
  • 14 - 4
  • 22 - 1 etc

但使用电流比较我只得到这样一个结果:

  • 12 - 8
  • 12 - 3
  • 13 - 1
  • 14 - 4
  • 14 - 2
  • 22 - 3
  • 22 - 2
  • 22 - 1

是否有一个舒适的方式来做到这一点的代码块?我可以想象的另一种方法是将列表拆分为子列表并将它们分开排序并将它们粘合在一起,但这可能需要更高的计算能力

+0

如果你正在返回相同的值什么是如果循环检查比较是相同的? –

+0

你的问题看起来类似于这个http://stackoverflow.com/questions/15610434/sorting-array-based-on-custom-object-values/15611004#15611004 –

+0

你也可以这样做: NSSortDescriptor * firstSorter = [[NSSortDescriptor alloc] initWithKey:@“firstProperty”升序:YES]; NSSortDescriptor * secondSorter = [[NSSortDescriptor alloc] initWithKey:@“secondProperty”升序:YES]; NSArray * sortedArray = [array sortedArrayUsingDescriptors:@ [firstSorter,secondSorter]]; –

回答

0

您应该首先比较两个对象的attr_a。如果它们相等,比较两个对象的attr_b

NSComparisonResult comp = [o1.attr_a compare:o2.attr_a]; 
if (comp == NSOrderedSame) { 
    comp = [o1.attr_b compare:o2.attr_b];  
} 
return comp; 

(。您的代码进行比较的第一个对象attr_a与第二对象,这并没有多大意义的attr_b

+0

对不起,我刚刚在代码中发现了一个错误:刚刚发布的就是这个。这似乎并不是它。我比较attr_a,如果他们是相同的我比较attr_b和返回分别。 – fletcher

相关问题