NSDictionary 为不同的键返回相同的值

问题描述 投票:0回答:1

我有一些 Obj-C 代码,它们使用

NSNumber
作为字典中的键。我发现了一个错误,我追踪到一些非常奇怪的行为,如果使用
NSDecimalNumber
NSNumber
的子类)访问字典,它总是返回相同的元素。这是一个小程序,它展示了该行为,并且 NSLogs 输出了问题:

#define LONGNUMBER1 5846235266280328403
#define LONGNUMBER2 5846235266280328404
- (void) wtfD00d {
    NSMutableDictionary *dict = [NSMutableDictionary dictionary];

    NSNumber *key1 = [NSNumber numberWithLongLong:LONGNUMBER1];
    NSNumber *key2 = [NSNumber numberWithLongLong:LONGNUMBER2];
    dict[key1] = @"ONE";
    dict[key2] = @"TWO";

    NSNumber *decimalKey1 = [NSDecimalNumber numberWithLongLong:LONGNUMBER1];
    NSNumber *decimalKey2 = [NSDecimalNumber numberWithLongLong:LONGNUMBER2];
    NSString *value1 = dict[decimalKey1];
    NSString *value2 = dict[decimalKey2];

    NSLog(@"Number of entries in dictionary = %lu", (unsigned long)dict.count); // 2
    NSLog(@"%@", dict);  //  5846235266280328403 = ONE
                         //  5846235266280328404 = TWO
    NSLog(@"Value1 = %@, Value 2 = %@", value1, value2);   // Value1 = ONE, Value 2 = ONE
    NSLog(@"key2 = decimalKey2: %@", [key2 isEqual:decimalKey2] ? @"True" : @"False");  // key2 isEqual decimalKey2: True
    NSLog(@"decimalKey1 = decimalKey2: %@", [decimalKey1 isEqual:decimalKey2] ? @"True" : @"False");  // decimalKey1 isEqual decimalKey2: False
}

请注意,第三条日志行显示 value1 和 value2 相同。为什么会出现这种情况?

出现这个问题是因为 CoreData 中有一些 Decimal 类型的字段,它们以 NSNumber 的形式从 CoreData 中出来。我们发现我们必须玩游戏来解决这种奇怪的行为,我不明白为什么它首先会发生。我希望任何人都可以提供有关查找失败原因的任何见解。

objective-c nsdictionary nsnumber
1个回答
2
投票

我认为当

NSNumber
NSDecimalNumber
相互比较时,他们是在用
doubleValue
进行比较。

您可以报告苹果的错误

我只能建议避免

NSNumber<->NSDecimalNumber
比较并在此处使用:

NSString *value1 = dict[@(decimalKey1.longLongValue)];
NSString *value2 = dict[@(decimalKey2.longLongValue)];
© www.soinside.com 2019 - 2024. All rights reserved.