gpt4 book ai didi

ios - 当作为对象添加到 NSDictionary 时,NSNumber numberWithInt 结果为 NSNull

转载 作者:行者123 更新时间:2023-11-29 03:28:45 25 4
gpt4 key购买 nike

这可能是一个相当基本的问题,但尽我所能,我找不到导致它的原因。

我编写了以下代码:

    NSMutableDictionary * myDictionary = [[NSMutableDictionary alloc] init];
NSMutableArray * values = [[NSMutableArray alloc] init];

for (int i=0; i<10; i++) {

// create an object that can become a key in an NSDictionary
CustomObjectAdoptingNSCopy * someKey = [[CustomObjectAdoptingNSCopy alloc] init];

// create a random value that will become an object for myDictionary ...
int someValue = rand()%10;

// ... and which also gets to be an object in the values array, provided it isn't already stored there
if ([values indexOfObject:[NSNumber numberWithInt:someValue]]==NSNotFound)
[values addObject:[NSNumber numberWithInt:someValue]];

// now associate someValue with someKey in myDictionary
[myDictionary setObject:[NSNumber numberWithInt:someValue] forKey:someKey];
}

// read the data in myDictionary enumerating the NSArray values
for (NSNumber * aValue in values){
NSArray * objectsForValue = [myDictionary allKeysForObject:aValue];
// now the data from objectsForValue are being used ...
}

objectsForValue为空时,问题就会出现,这种情况不会一直发生,而是经常发生。如果我没有弄错的话,这在逻辑上是不可能的,除非当将 [NSNumber numberWithInt:someValue] 作为对象添加到 myDictionary 时被解释为 NSNull,而相同的表达式被视为一个对象被添加到 NSArray values 中时。

并记录myDictionary我注意到这确实是正在发生的事情。谁能给我解释一下为什么吗?

最佳答案

如果您尚未覆盖 -isEqual:-hash,则 CustomObjectAdoptingNSCopy 的副本彼此不相等。 NSObject 平等的默认实现是对象标识。由于 NSDictionary 复制键,但副本不等于原始键,因此您无法从字典中检索任何内容,除非您向字典询问其键并使用它们。原来的不行。

关于ios - 当作为对象添加到 NSDictionary 时,NSNumber numberWithInt 结果为 NSNull,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20107315/

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