应用两个排序不能正常工作

Mal*_*loc 1 sorting objective-c ios

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

应用这两种排序似乎不起作用,但是,应用其中一种工作正常,所以如果我按价格应用排序,它将返回按价格排序的产品,标题相同的东西.那么为什么我无法按价格和头衔排序呢?

//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;

}
Run Code Online (Sandbox Code Playgroud)

ika*_*ver 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];
}];
Run Code Online (Sandbox Code Playgroud)

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