我试图按价格先按标题排序大量产品,然后显示:
应用两种排序似乎都不起作用,但是,应用其中一种方法可以正常工作,因此如果我按价格应用排序,它将返回按价格排序的产品,标题相同。那么为什么我无法按价格和头衔进行排序呢?
//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;
}
答案 0 :(得分: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)
答案 1 :(得分:1)
我认为这里的问题是你按价格排序一次,然后按标题求助整个数组,覆盖第一轮完成的任何排序。看来你想要的是一个按价格排序的数组,如果两个或多个项目的价格相同,那么该子集将按标题排序。要做到这一点,您应该只排序一次,因此只有一个Comparator
功能。你基本上需要结合你拥有的两个。首先使用价格逻辑,但如果v1 == v2
则使用标题逻辑。