使用NSException类型的未捕获异常终止:尝试从对象插入nil对象[1]

时间:2017-02-18 12:55:01

标签: ios iphone xcode

当我的应用执行以下内容时,我会收到:terminating with uncaught exception of type NSException

NSDictionary *temporary = nil;
if(eventName != nil) {
  NSLog(@"nil found -----> ");
  temporary = @{@"eventname": @"OK",
                              @"type": dictionary[@"type"],
                              @"from"  : dictionary[@"from"],
                              @"to"  : dictionary[@"to"]};
}
else {
  NSLog(@"OK no nil found -----> ");
  temporary = @{@"eventname": @"?????",
                              @"type": dictionary[@"type"],
                              @"from"  : dictionary[@"from"],
                              @"to"  : dictionary[@"to"]};
}

ERROR:

2017-02-18 13:49:26.411903 ios[3645:1360486] [DYMTLInitPlatform] platform initialization successful
2017-02-18 13:49:26.543678 ios[3645:1360413] Metal GPU Frame Capture Enabled
2017-02-18 13:49:26.544129 ios[3645:1360413] Metal API Validation Enabled
2017-02-18 13:49:26.689675 ios[3645:1360413] [MC] System group container for systemgroup.com.apple.configurationprofiles path is /private/var/containers/Shared/SystemGroup/systemgroup.com.apple.configurationprofiles
2017-02-18 13:49:26.691524 ios[3645:1360413] [MC] Reading from public effective user settings.
2017-02-18 13:49:26.998874 ios[3645:1360413] eventName = servers, type = (null), from = (null), to = (null)
2017-02-18 13:49:26.998919 ios[3645:1360413] nil found -----> 
2017-02-18 13:49:26.999137 ios[3645:1360413] *** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '*** -[__NSPlaceholderDictionary initWithObjects:forKeys:count:]: attempt to insert nil object from objects[1]'
*** First throw call stack:
(0x18c9b51b8 0x18b3ec55c 0x18c898eac 0x18c898d1c 0x1000fc2b8 0x1000f92cc 0x1000e58e0 0x18d4c9048 0x18c962b5c 0x18c9624a4 0x18c9600a4 0x18c88e2b8 0x18e342198 0x1928d57fc 0x1928d0534 0x1000a1f48 0x18b8715b8)
libc++abi.dylib: terminating with uncaught exception of type NSException
(lldb) 

2 个答案:

答案 0 :(得分:1)

  

- [__ NSPlaceholderDictionary initWithObjects:forKeys:count:]:尝试从对象中插入nil对象[1]'

您的问题:

您正在尝试向nil NSDictionary插入temporary个对象。

如果您尝试插入NSDictionary个对象,

nil会崩溃。 但您可以向其中插入NSNull

您的解决方案:

对于您不确定的每个密钥,请执行此类操作,以防止崩溃(如果是字符串,则执行等效检查):

id fromObject = fromString.length ? fromString : [NSNull null];

只需将fromObject插入NSDictionary,即使它是nil,也不会崩溃。

@"from"  : fromObject,

答案 1 :(得分:1)

错误信息非常清楚:

  

尝试从对象[1]

插入nil对象

字典中的所有值都不能为nil,但显然键typefromto 的值之一 nil,根据打印输出,即使这三个都是( eventName = servers,type =(null),from =(null),to =(null))。