1

iOS6 SDK下NSUserDefaults异常原因,异常如下:

*** 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"];应用程序运行良好。

任何人都可以帮忙吗?非常感谢!

4

2 回答 2

1

如果添加日志消息,您会发现版本字符串为 nil。您不能将 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 :-(");
于 2012-09-24T11:40:08.487 回答
1

我注册了一个NSUserDefaultsDidChangeNotification通知,如果更改 NSUserDefaults 设置,则调用通知方法。有些变量在第一次启动之前是 nil,我将这些变量保存到 NSUserDefaults,所以发生了崩溃。

于 2012-09-25T02:15:42.800 回答