6

我正在尝试对一个数组进行排序NSObjects(一个对象属于一个类)。对象类有几个变量,我想用它们对数组中的对象进行排序,我用来排序的变量是NSStringor NSInteger,我相信我正在排序 NSStrings 但对于这个问题,我希望得到帮助排序一个NSInteger

这是我用来对对象数组进行排序的方法,它接收一个NSMutableArray对象

- (NSMutableArray *)startSortingTheArray:(NSMutableArray *)unsortedArray
{
    [unsortedArray sortUsingComparator:^ NSComparisonResult(SearchResultItem *d1, SearchResultItem *d2) {
        NSInteger DoorID1 = d1.doorID;
        NSInteger DoorID2 = d2.doorID;
        NSComparisonResult result = [DoorID1 localizedCompare:DoorID2]; // Not sure how to sort these two integers
        if (result == NSOrderedSame) {
            NSString *handel1 = d1.handel;
            NSString *handel2 = d2.handel;
            result = [handel1 localizedCompare:handel2];
         }

我不知道如何比较 NSInteger,我已经读过我可以从自身中减去每个数字。如果数字为 0,那么它们相等或 +1 / -1 等它们不相等。但不确定这是否是解决这个问题的最佳方法。

任何帮助,将不胜感激。

4

4 回答 4

19
[unsortedArray sortUsingComparator:^ NSComparisonResult(SearchResultItem *d1, SearchResultItem *d2) {
    NSInteger doorID1 = d1.doorID;
    NSInteger doorID2 = d2.doorID;
    if (doorID1 < doorID2)
        return NSOrderedAscending;
    if (doorID1 > doorID2)
        return NSOrderedDescending;
    return [d1.handel localizedCompare: d2.handel];
}];

因为[aString localizedCompare:anotherString]将返回 NSOrdered(Ascending|Descending|same),您可以只返回字符串大小写的结果。

于 2012-08-14T00:08:29.757 回答
2

另外的选择:

NSComparisionResult res = [@(d1.doorID) compare:@(d2.doorID)];
return res == NSOrderedSame ? [d1.handel localizedCompare: d2.handel] : res;
于 2014-10-13T14:06:26.580 回答
2

AnNSInteger不是对象。它只是一个整数( anint或 a long)。因此,您可以准确地比较它们如何比较两个ints。

经典的 C 比较函数可以让您做到这一点x - y,但这在这里不合适,因为您将返回一个不适合NSComparisonResult枚举的整数。因此,您可能应该只做类似的事情

if (DoorID1 == DoorID2) {
    // compare secondary attribute
    NSString *handel1 = d1.handel;
    NSString *handel2 = d2.handel;
    return [handel1 localizedCompare:handel2];
}
else if (DoorID1 < DoorID2) return NSOrderedAscending;
else return NSOrderedDescending;

顺便说一句,您的排序标准可以用NSSortDescriptor代替表示,这可能更清楚。

- (NSMutableArray *)startSortingTheArray:(NSMutableArray *)unsortedArray {
    NSSortDescriptor *primary = [NSSortDescriptor sortDescriptorWithKey:@"doorID" ascending:YES];
    NSSortDescriptor *secondary = [NSSortDescriptor sortDescriptorWithKey:@"handel" ascending:YES selector:@selector(localizedCompare:)];
    [unsortedArray sortUsingDescriptors:@[primary, secondary]];
}
于 2012-08-14T00:07:56.727 回答
1
[unsortedArray sortUsingComparator:^ NSComparisonResult(SearchResultItem *d1, SearchResultItem *d2) {
    NSInteger doorID1 = d1.doorID;
    NSInteger doorID2 = d2.doorID;
    if (doorID1 > doorID2)
        return NSOrderedAscending;
    if (doorID1 < doorID2)
        return NSOrderedDescending;
    if (doorID1==doorID2) {
        NSString *s1=d1.someString;
        NSString *s2=d2.someString;
        return [s1 compare:s2];
    }
}
于 2012-08-14T00:35:43.317 回答