[英]applying two sorting doesn't work properly
我試圖先按價格對大范圍的產品進行排序,然后按標題對它們進行排序,然后顯示它們:
但是,同時應用兩種排序似乎都行不通,但是,如果只應用其中一種,則效果很好,因此,如果我按價格應用排序,它將返回按價格排序的產品,標題也一樣。 那么,為什么我不能同時按價格和標題分類?
//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 )
我認為這里的問題是,您要按價格排序一次,然后按標題重新排序整個數組,從而覆蓋第一輪完成的所有排序。 似乎您想要的是一個按價格排序的數組,如果兩個或多個項目的價格相同,則該子集將按標題排序。 為此,您應該只排序一次,因此只有一個Comparator
函數。 您本質上需要將兩者結合起來。 首先使用價格邏輯,但如果v1 == v2
則將邏輯用於標題。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.