NSUserDefaults
导致iOS6 SDK下的异常,例外情况如下:
*** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '*** -[__NSPlaceholderDictionary initWithObjects:forKeys:count:]: attempt to insert nil object from objects[0]'
*** First throw call stack:
(0x3527a2a3 0x32d7a97f 0x351cb55f 0x352020d3 0xe2f9d 0x351cb037 0x372a1d91 0x372aa13b 0xcd813 0x34e36f1f 0x34e379a9 0x36d5d35d 0x3524f173 0x3524f117 0x3524df99 0x351c0ebd 0x351c0d49 0x32e762eb 0x34c38301 0xcc20f 0xc5e40)
libc++abi.dylib: terminate called throwing an exception
这是代码:
NSUserDefaults *ud = [NSUserDefaults standardUserDefaults];
NSString *shortVersionString = [[[NSBundle mainBundle] infoDictionary] objectForKey:@"CFBundleShortVersionString"];
// the shortVersionString is 2.0.1
[ud setBool:YES forKey:@"hasBeenLaunched"];
[ud setObject:shortVersionString forKey:@"CurrentVersion"];
如果我发表评论[ud setBool:YES forKey:@"hasBeenLaunched"];
和[ud setObject:shortVersionString forKey:@"CurrentVersion"];
,该应用就可以正常使用。
任何人都可以提供帮助?非常感谢!
答案 0 :(得分:1)
如果添加日志消息,您会发现版本字符串为nil。你不能在默认值上写一个零,这就是失败的原因:
NSString *shortVersionString = [[[NSBundle mainBundle] infoDictionary] objectForKey:@"CFBundleShortVersionString"];
NSLog(@"Bet this is nil: %@", shortVersionString);
NSLog(@"Get ready for crash");
[ud setObject:shortVersionString forKey:@"CurrentVersion"];
NSLog(@"Guess I was wrong - no crash :-(");
答案 1 :(得分:1)
我注册NSUserDefaultsDidChangeNotification
通知,如果更改NSUserDefaults设置,则调用通知方法。在第一次启动之前,一些变量是nil,我将这些变量保存到NSUserDefaults,因此发生了崩溃。