gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-01 17:20:47 24 4
gpt4 key购买 nike

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

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

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

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com