1

我试图先按价格然后按标题对大量产品进行排序,然后显示它们:

应用这两种排序似乎不起作用,但是,应用其中一种效果很好,所以如果我应用按价格排序,它将返回按价格排序的产品,标题也是如此。那么为什么我不能同时按价格和标题排序呢?

//Sort by Price, then by Title. Both Ascending orders
arrayProduct = (NSMutableArray*)[arrayProduct sortedArrayUsingFunction:priceComparator context:nil];
arrayProduct = (NSMutableArray*)[arrayProduct sortedArrayUsingFunction:titleComparator context:nil];


//products comparators
NSInteger priceComparator(NSMutableDictionary *obj1, NSMutableDictionary *obj2, void *context){


    int v1 = [[[obj1 valueForKey:@"Product Sale Price"]substringFromIndex:1] intValue];
    int v2 = [[[obj2 valueForKey:@"Product Sale Price"]substringFromIndex:1] intValue];

    if (v1 < v2){

        return NSOrderedAscending;
    }
    else if (v1 > v2){

        return NSOrderedDescending;

    }
    else
        return NSOrderedSame;

}

NSInteger titleComparator(NSMutableDictionary *obj1, NSMutableDictionary *obj2, void *context){

    NSString* v1 = [obj1 valueForKey:@"Product Title"];
    NSString* v2 = [obj2 valueForKey:@"Product Title"];

    if ([v1 caseInsensitiveCompare:v2] == NSOrderedAscending){

        return NSOrderedAscending;
    }
    else if ([v1 caseInsensitiveCompare:v2] == NSOrderedDescending){

        return NSOrderedDescending;
    }
    else
        return NSOrderedSame;

}
4

2 回答 2

9

您得到的结果不正确,因为您对整个数组进行了两次排序。以下是一些其他选项:

你可以使用积木

[arrayProduct sortUsingComparator:^NSComparisonResult(id a, id b) {
    NSMutableDictionary * dictA = (NSMutableDictionary*)a;
    NSMutableDictionary * dictB = (NSMutableDictionary*)b;

    NSInteger p1 = [[[dictA valueForKey:@"Product Sale Price"]substringFromIndex:1] integerValue];
    NSInteger p2 = [[[dictB valueForKey:@"Product Sale Price"]substringFromIndex:1] integerValue];

    if(p1 > p2){
        return NSOrderedAscending;
    }
    else if(p2 > p1){
        return NSOrderedDescending;
    }
    //Break ties with product titles
    NSString* v1 = [dictA valueForKey:@"Product Title"];
    NSString* v2 = [dictB valueForKey:@"Product Title"];

    return [v1 caseInsensitiveCompare:v2];
}];

或 NSSortDescriptors ( http://developer.apple.com/library/ios/documentation/cocoa/Conceptual/SortDescriptors/Articles/Creating.html )

于 2013-08-14T16:41:24.317 回答
1

我认为这里的问题是您按价格排序一次,然后按标题对整个数组进行排序,覆盖第一轮完成的任何排序。看起来你想要的是一个按价格排序的数组,如果两个或多个项目的价格相同,则该子集将按标题排序。为此,您应该只排序一次,因此只有一个Comparator功能。您基本上需要将您拥有的两者结合起来。首先使用价格逻辑,v1 == v2然后使用标题逻辑。

于 2013-08-14T16:30:05.307 回答