编辑: 正如我想的那样,甚至没有问题,我只是使用错误的值来检查我的结果。无法使用自定义比较器对两个属性进行排序
我比较我的数据库的自定义对象和排序它们的目标有点麻烦,原则上,这很容易,排序机制必须与这个自定义对象的两个属性由字符串表示,但也可以包含数值。
这是我正在尝试修复的自定义比较器块。
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
是否有一个舒适的方式来做到这一点的代码块?我可以想象的另一种方法是将列表拆分为子列表并将它们分开排序并将它们粘合在一起,但这可能需要更高的计算能力
如果你正在返回相同的值什么是如果循环检查比较是相同的? –
你的问题看起来类似于这个http://stackoverflow.com/questions/15610434/sorting-array-based-on-custom-object-values/15611004#15611004 –
你也可以这样做: NSSortDescriptor * firstSorter = [[NSSortDescriptor alloc] initWithKey:@“firstProperty”升序:YES]; NSSortDescriptor * secondSorter = [[NSSortDescriptor alloc] initWithKey:@“secondProperty”升序:YES]; NSArray * sortedArray = [array sortedArrayUsingDescriptors:@ [firstSorter,secondSorter]]; –