ios - 应用两次排序无法正常工作

标签 ios objective-c sorting

我想先按价格对大范围的产品进行排序,然后按标题对它们进行排序,然后显示它们:

但是,同时应用两种排序似乎都行不通,但是,如果只应用其中一种,则效果很好,因此,如果我按价格应用排序,它将返回按价格排序的产品,标题也一样。那么,为什么我不能同时按价格和标题分类?

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

}

最佳答案

由于对整个数组进行了两次排序,因此结果不正确。以下是一些其他选项:

你可以用块

[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)

关于ios - 应用两次排序无法正常工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18237080/

相关文章:

iphone - 将单独的 iPhone 和 iPad 项目转换为通用项目

objective-c - 使用带有 NSString 的 XCTAssertEqual 作为错误消息参数

ios - 当应用程序返回前台时删除任何弹出窗口

mysql - 有条件地更改 SQL 中的排序方向

Python:排序函数的参数

IOS Swift 如何在 subview 之上添加元素

ios - 过渡时的 fatal error

ios - UITabBar 在应用程序启动时将所有图标显示为 "selected"模式

ios - OneSignal 发布通知失败

Java 排序日期字段