且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

NSUserDefaults在iOS 8中不可靠

更新时间:2023-02-09 23:05:13

iOS 8引入了许多行为更改 NSUserDefaults的。虽然 NSUserDefaults API变化不大,但行为已经以与您的应用程序相关的方式发生了变化。例如,不建议使用 -synchronize (并且一直都是这样)。对Foundation和CoreFoundation的其他部分(例如文件协调)以及与共享容器相关的更改的添加更改可能会影响您的应用程序以及您使用 NSUserDefaults

iOS 8 introduced a number of behavior changes to NSUserDefaults. While the NSUserDefaults API has changed little, the behavior has changed in ways that may be relevant to your application. For example, using -synchronize is discouraged (and always has been). Addition changes to other parts of Foundation and CoreFoundation such as File Coordination and changes related to shared containers may affect your application and your use of NSUserDefaults.

写入 NSUserDefaults 尤其因此而改变。写入需要更长时间,并且可能有其他进程竞争访问应用程序的用户默认存储。如果您在应用程序退出时尝试写入 NSUserDefaults ,则在某些情况下提交写入之前,您的应用程序可能会被终止。在您的示例中使用 exit(0)强制终止很可能会刺激此行为。通常,当退出应用程序时,系统可以执行清理并等待未完成的文件操作完成 - 当您使用 exit()或调试器终止应用程序时,这可能不会发生。

Writing to NSUserDefaults in particular has changed because of this. Writing takes longer, and there may be other processes competing for access to the application's user defaults storage. If you are attempting to write to NSUserDefaults as your application is exiting, your application may be terminated before the write is committed under some scenarios. Forcefully terminating using exit(0) in your example is very likely to stimulate this behavior. Normally when an application is exited the system can perform cleanup and wait for outstanding file operations to complete - when you are terminating the application using exit() or the debugger this may not happen.

一般来说, NSUserDefaults 在iOS 8上正确使用时是可靠的。

In general NSUserDefaults is reliable when used correctly on iOS 8.

这些更改在 OS X 10.10的基础发行说明(目前没有针对iOS 8的单独的Foundation发行说明)。

These changes are described in the Foundation release notes for OS X 10.10 (currently there is not a separate Foundation release note for iOS 8).