我的 iOS 应用程序因 Thread 1: signal SIGABRT
错误而终止。奇怪的是,当我将光标悬停在 NSNumber 对象(发生错误的地方)上时,它会显示带有键/值对的 NSDictionary 对象。以下是我的代码片段:
for(id obj in [MainDict allKeys])
{
NSArray *AnArrayInsideMainDict = [MainDict objectForKey:obj];
double i=1;
for(NSUInteger n=0; n<4; n++)
{
NSNumber *anObject = [AnArrayInsideMainDict objectAtIndex:n];
NSNumber *nextObject = [nextDict objectForKey:[NSNumber numberWithDouble:i]];
NSNumber *HereIsTheError = [NSNumber numberWithFloat:(powf(([anObject floatValue]-[nextObject floatValue]),2))];
[ThisIsMutableArray addObject:HereIsTheError];
i++
}
}
这里,MainDict
包含 64 个键/值对(每个键包含一个包含 5 个对象的 NSArray
)。nextDict
是一个 NSDictionary 4 个键/值对(每个键包含一个 NSNumber
对象//编辑:每个键实际上包含一个带有单个 NSNumber 对象的 NSArray ,这就是错误的原因)。应用程序终止并将光标悬停在 HereIsTheError
上后,我得到以下键/值对:
控制台的终止错误是:
*** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[__NSArrayM floatValue]: unrecognized selector sent to instance 0x170257a30'
*** First throw call stack:
(0x18b032fe0 0x189a94538 0x18b039ef4 0x18b036f54 0x18af32d4c 0x1000891a0 0x10008bd74 0x10020d598 0x100579a50 0x100579a10 0x10057eb78 0x18afe10c8 0x18afdece4 0x18af0eda4 0x18c979074 0x1911c9c9c 0x1000906b4 0x189f1d59c)
libc++abi.dylib: terminating with uncaught exception of type NSException
(lldb)
NSNumber
如何构造NSDictionary
的对象?我使用 Xcode 版本 9.0.1 (9A1004) 和 Objective-C。
最佳答案
正如评论所述,但最重要的是你的错误消息指出,你的对象 anObject
和 nextObject
不是 NSNumber
- 它们是 NSMutableArray
,因此是
-[__NSArrayM floatValue]: unrecognized selector...
你的部分错误。
确保 AnArrayInsideMainDict
中的对象实际上是
NSNumber
在尝试将它们转换为数字之前,
我建议在“假定”它们的类型之前标记您的对象,但我怀疑这是否会帮助您获得所需的结果(因为这很可能从您的案例中跳过每个不是的对象一个 NSNumber
)。
甚至在你进入 [MainDict allKeys]
中的 for 循环之前,回溯 以确保你实际上传递的是 NSNumber
数组' s 作为字典对象。
如果您实际上不确定对象类型,您可以只是抛出一个标志以确保您没有误解任何对象:
...
for (NSUInteger n=0; n<4; n++) {
NSNumber *anObject = [AnArrayInsideMainDict objectAtIndex:n];
NSNumber *nextObject = [nextDict objectForKey:[NSNumber numberWithDouble:i]];
if ([anObject isKindOfClass:NSNumber.class] && [nextObject isKindOfClass:NSNumber.class]) {
// Good to continue now that you know the objects
} else NSLog(@"whoops.. anObject: %@ nextObject: %@", anObject.class, nextObject.class);
...
最后,如果您胆大包天,并且确定这本词典中的某处是您的NSNumber
,您可以标记您的步骤以检查NSNumber.class
来寻找你的花车。
否则,我建议深入研究如何和从哪里您是从哪里获取MainDict
的。
快乐的编码 - 干杯!
关于ios - NSNumber 在 Objective-C 中存储 NSDictionary 的对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50152071/