NSUserDefaults 何时以及为什么会出现?同步方法失败?
NSUserDefaults 的同步方法何时以及为何失败?确保我的值实际写入并提交给 NSUserDefaults 的最佳方法是什么,这样我在应用程序重新启动后恢复状态就不会遇到任何问题?
When and why does NSUserDefaults' synchronize method fail? What is the best way to make sure that my values are actually written and commited to NSUserDefaults, so I wouldn't have any problems restoring state after application restart?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
synchronize
方法是围绕CFPreferencesSynchronize
函数的更高级别 API 包装器。文档中没有任何相关内容,但我认为synchronize
只是返回CFPreferencesSynchronize
的结果。由于此 CoreFoundation 功能可用于同步主机(管理员)和基于网络的首选项,因此在某些情况下可能会失败。在最常见的情况下,应用程序只是同步其用户域首选项(在当前用户的 Library 目录中),该功能通常不会失败。我认为忽略
synchronize
的返回值是安全的。但这只是我的意见。The
synchronize
method is a higher level API wrapper around theCFPreferencesSynchronize
function. There's nothing about it in the documentation but I presume thatsynchronize
just returns the result ofCFPreferencesSynchronize
. Since this CoreFoundation function can be used to synchronize host (admin) and network based preferences it can fail in some cases.In the most common case where an app just synchronizes its user domain preferences (in the Library directory of the current user), the function usually does not fail. I think it's safe to just ignore the return value of
synchronize
. But that's just my opinion.在某些情况下,我的应用程序尝试使用某个键写入 nil 值,这导致同步失败。现在我在保存之前检查该值是否为零,问题已解决。
In some cases, my app was trying to write a nil value with a certain key, and that was causing synchronize to fail. Now I'm checking that value for nil before the save and the problem is fixed.
就我而言,我错误地使用了 NSUserDefaults,并且它会失败。
比如我定义自己的对象,放到NSUserDefaults或者NSDictionary里,可以放到,但是同步的时候会失败。因为 NSUserDefaults 并不支持所有类型的对象。
据我所知,NSString,NSNumber,NSDictionary ....你可以google一下如何使自定义类可以存储在NSUserDefaults中。
In my cases, I wrongly use NSUserDefaults, and it will fail.
For example, I define my own object, and put it into NSUserDefaults or NSDictionary, it can be put, but it will fail when synchronize. Because NSUserDefaults doesn't support every kind of object.
As I know, NSString, NSNumber, NSDictionary....you can google it how to make custom class can be stored in NSUserDefaults.