在开始之前,我应该告诉您,这仅发生在 iOS 5.1 中。在最近的更新之前,这从未发生过,而且在任何其他版本上也不会发生。也就是说,这就是发生的事情。
当用户注销我的应用程序时,发生的事情之一是所有 NSUserDefaults
都被删除。我没有手动删除可能添加到用户默认值的每个键,而是使用 this SO question 中建议的方法完全删除所有 NSUserDefaults
:
NSString *appDomain = [[NSBundle mainBundle] bundleIdentifier];
[[NSUserDefaults standardUserDefaults] removePersistentDomainForName:appDomain];
虽然似乎发生了什么,但每次我在删除 NSUserDefaults
后尝试创建一个 UIWebView
时,我都会得到一个 EXC_CRASH (SIGABRT)
。当我调用 [[UIWebView alloc] initWithFrame:frame]
时发生崩溃。奇怪吧?完全退出并重新打开应用程序允许再次创建 UIWebView
。
因此,我设法弄清楚删除默认值会导致 UIWebView
问题,但可以肯定的是,我为 -[NSUserDefaults setObject:forKey:]< 添加了一个符号断点
。
创建 UIWebView
确实会触发断点。
查看崩溃日志给出了异常原因:
-[__NSCFDictionary setObject:forKey:]: attempt to insert nil value (key: WebKitLocalStorageDatabasePathPreferenceKey)
这是堆栈跟踪的开始:
0 CoreFoundation 0x3340688f __exceptionPreprocess + 163
1 libobjc.A.dylib 0x37bd4259 objc_exception_throw + 33
2 CoreFoundation 0x33406789 +[NSException raise:format:] + 1
3 CoreFoundation 0x334067ab +[NSException raise:format:] + 35
4 CoreFoundation 0x3337368b -[__NSCFDictionary setObject:forKey:] + 235
5 WebKit 0x3541e043 -[WebPreferences _setStringValue:forKey:] + 151
6 UIKit 0x32841f8f -[UIWebView _webViewCommonInit:] + 1547
7 UIKit 0x328418d7 -[UIWebView initWithFrame:] + 75
8 MyApp 0x0007576f + 0
9 UIKit 0x326d4dbf -[UIViewController view] + 51
10 UIKit 0x327347e5 -[UITabBarController transitionFromViewController:toViewController:transition:shouldSetSelected:] + 93
11 UIKit 0x32734783 -[UITabBarController transitionFromViewController:toViewController:] + 31
12 UIKit 0x327340bd -[UITabBarController _setSelectedViewController:] + 301
13 UIKit 0x327bd5d9 -[UITabBarController _tabBarItemClicked:] + 345
我现在正在做的和有效的,只是跟踪我设置的 NSUserDefaults
键,并在需要时手动删除它们。但是总是存在我可能会忘记敏感 key 的风险,因此简单地清除所有 NSUserDefaults
让我觉得更明智。所以,我想知道为什么我不能这样做。是错误还是我做错了什么?
如果您想了解更多信息,请告诉我!谢谢。
编辑:在删除所有 NSUserDefaults
后执行 [[NSUserDefaults standardUserDefaults] synchronize]
没有帮助。
最佳答案
我也看到了这个问题,我认为您必须先创建一个 UIWebView,然后才能清除用户默认值,它才会发生。具有以下内容的干净项目将导致 iOS5.1 崩溃,这在 iOS5.0 及更早版本中工作正常:
UIWebView *webView = [[UIWebView alloc] init];
[webView release];
[[NSUserDefaults standardUserDefaults] setPersistentDomain:[NSDictionary dictionary] forName:[[NSBundle mainBundle] bundleIdentifier]];
UIWebView *anotherWebView = [[UIWebView alloc] init];
[anotherWebView release];
我可以通过这样做来解决崩溃问题,这样就不必记住所有设置键:
id workaround51Crash = [[NSUserDefaults standardUserDefaults] objectForKey:@"WebKitLocalStorageDatabasePathPreferenceKey"];
NSDictionary *emptySettings = (workaround51Crash != nil)
? [NSDictionary dictionaryWithObject:workaround51Crash forKey:@"WebKitLocalStorageDatabasePathPreferenceKey"]
: [NSDictionary dictionary];
[[NSUserDefaults standardUserDefaults] setPersistentDomain:emptySettings forName:[[NSBundle mainBundle] bundleIdentifier]];
有人发现这样做有什么问题吗?
关于iphone - 为什么在创建 UIWebView 时清除 NSUserDefaults 会导致 EXC_CRASH?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9679163/