基于 an NSMutableArray
of NSMutableDictionary
s,我尝试根据 key 按升序对其进行排序。密钥被调用Product Sale Price
,它作为字符串从服务器返回,如$350
. 所以我对第一个字符进行子串化以比较 int 值:
//Sorting function
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];
NSLog(@"v1, v2: %i | %i",v1,v2);
if (v1 > v2){
NSLog(@"v2 is smaller: <%i>",v2);
return v2;
}
else if (v1 < v2){
NSLog(@"v1 is smaller: <%i>",v1);
return v1;
}
else
return NSOrderedSame;
}
//Somewhere in the code
arrayProduct = (NSMutableArray*)[arrayProduct sortedArrayUsingFunction:priceComparator context:nil];
NSLog(@"%@",arrayProduct);//The array is not sorted as expected, still random order
所以基本上,尽管我调试了步骤 b 并且所有比较都是正确的,但顺序并没有受到某种影响。我错过了什么吗?
编辑:
以下是一些项目arrayProduct
:
(
{
"Product ID" = 15119;
"Product Sale Price" = "$395";
},
{
"Product ID" = 16897;
"Product Sale Price" = "$75";
}
)