【发布时间】:2013-08-14 16:19:47
【问题描述】:
我正在尝试先按价格然后按标题对大量产品进行排序,然后再显示它们:
应用这两种排序似乎不起作用,但是,应用其中一种效果很好,所以如果我应用按价格排序,它将返回按价格排序的产品,标题也是如此。那么为什么我不能同时按价格和标题排序呢?
//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;
}
【问题讨论】:
-
我不相信
sortedArrayUsingFunction:context:保证保留元素的任何“次要”顺序。来自文档:“返回一个新数组,该数组按比较函数比较器定义的升序列出接收数组的元素。” -
那么,按两个参数(价格然后标题)对数组进行排序的更好方法是什么?
标签: ios objective-c sorting