原因
昨天app上的广告系统在做比价策略,小伙伴遇到了关于在NSDictionary keysSortedByValueUsingComparator 比较的时候遇到问题,总是随机出结果,不是自己想要的结果,所以记录一下。
总结如下
keysSortedByValueUsingComparator 比较的id _Nonnull obj1, id _Nonnull obj2 是两个临时变量,如果打印其地址会发现,可能每次输出的都相同,也可能不同。如果直接使用 if (obj1 > obj2) 则比较的是两个的变量的内存地址,因为iOS NSDictionary value 不能是int,所以需要转成NSNumber,那么比较的时候就不能简单比较了,需要拿到其value 进行比较 .
如下是正确的方法和测试案例
-
正确的方法
retArray = [dict keysSortedByValueUsingComparator:^NSComparisonResult(NSNumber * _Nonnull obj1, NSNumber * _Nonnull obj2) {
// NSLog(@"obj1 = %@ obj2 = %@",obj1,obj2);
// NSLog(@"obj1address = %x obj2 = %x",&obj1,&obj2);
if( obj1.intValue >= obj2.intValue){
//NSLog(@"compare obj1 = %d obj2 = %x",obj1.intValue,obj2.intValue);
// NSLog(@"compare obj1address = %x obj2 = %x",&obj1,&obj2);
return NSOrderedAscending;
}
return NSOrderedDescending;
}];
-
测试案例
NSMutableDictionary * dict = [NSMutableDictionary new];
for (int i =0; i<5; i++) {
dict[[NSString stringWithFormat:@"AD%d",arc4random()%100]]=@(arc4random()%1024);
}
NSLog(@"dict = %@",dict);
// 进行比价
// 第一种方案,结果发现不靠谱
/**
dict = {
AD27 = 67;
AD33 = 453;
AD39 = 389;
AD47 = 615;
AD87 = 696;
}
ret
key AD39-- value 389
key AD27-- value 67
key AD47-- value 615
key AD33-- value 453
key AD87-- value 696
*/
NSArray * retArray = [dict keysSortedByValueUsingComparator:^NSComparisonResult(id _Nonnull obj1, id _Nonnull obj2) {
return NSOrderedAscending;
}];
// 第二种方案,依旧错误
/**
dict = {
AD11 = 879;
AD79 = 63;
AD80 = 249;
AD84 = 86;
AD88 = 228;
}
key AD11-- value 879
key AD88-- value 228
key AD84-- value 86
key AD79-- value 63
key AD80-- value 249
*/
retArray = [dict keysSortedByValueUsingComparator:^NSComparisonResult(NSNumber * _Nonnull obj1, NSNumber * _Nonnull obj2) {
// NSLog(@"obj1address = %x obj2 = %x",&obj1,&obj2);
if( obj1 >= obj2){
// NSLog(@"compare obj1address = %x obj2 = %x",&obj1,&obj2);
return NSOrderedAscending;
}
return NSOrderedDescending;
}];
// 经过各种资料的调研发现,比较的 if( obj1 >= obj2) 仅仅是地址大小,所以如果想实现真正的价格比较应该是比NSNumber 的value值
/**
dict = {
AD17 = 809;
AD51 = 719;
AD52 = 640;
AD63 = 949;
AD7 = 852;
}
key AD63-- value 949
key AD7-- value 852
key AD17-- value 809
key AD51-- value 719
key AD52-- value 640
*/
retArray = [dict keysSortedByValueUsingComparator:^NSComparisonResult(NSNumber * _Nonnull obj1, NSNumber * _Nonnull obj2) {
// NSLog(@"obj1 = %@ obj2 = %@",obj1,obj2);
// NSLog(@"obj1address = %x obj2 = %x",&obj1,&obj2);
if( obj1.intValue >= obj2.intValue){
//NSLog(@"compare obj1 = %d obj2 = %x",obj1.intValue,obj2.intValue);
// NSLog(@"compare obj1address = %x obj2 = %x",&obj1,&obj2);
return NSOrderedAscending;
}
return NSOrderedDescending;
}];
for (NSString * key in retArray) {
NSLog(@"key %@-- value %@",key,dict[key]);
}
网友评论