gpt4 book ai didi

ios - sortedArrayUsingFunction 排序不正确

转载 作者:行者123 更新时间:2023-11-28 20:15:54 24 4
gpt4 key购买 nike

基于 NSMutableDictionaryNSMutableArray,我尝试根据键按升序对其进行排序。 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";
}
)

最佳答案

您需要返回 NSOrderedAscendingNSOrderedDescending 而不是 v1v2。如果排序以相反的顺序结束 - 交换返回的两个中的哪一个。

关于ios - sortedArrayUsingFunction 排序不正确,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18094962/

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