NSUserDefaults:+ resetStandardUserDefaults方法有什么好处?如何提供“系统设置”? [英] NSUserDefaults: What's the +resetStandardUserDefaults method good for? How can I provide "system settings"?

查看:1047
本文介绍了NSUserDefaults:+ resetStandardUserDefaults方法有什么好处?如何提供“系统设置”?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想让用户能够做一些偏好,比如颜色,优先的图片等。
当我使用NSUserDefaults为此,在应用程序的第一次启动将没有偏好​​,对吗?所以,每次我想获得一个喜欢

I want the user to be able to make some preferences like colors, prefered images, etc. When I use NSUserDefaults for this, on first start of the app there will be no preferences, right? So, every time I want to get a preference like

NSInteger avatarID =(NSInteger)[[NSUserDefaults standardUserDefaults] objectForKey:@avatar];

NSInteger avatarID = (NSInteger)[[NSUserDefaults standardUserDefaults] objectForKey:@"avatar"];

我必须检查它是否为空,然后使用我的系统首选项。但是我已经在文档中看到这个:+ resetStandardUserDefaults

I have to check if it's null, and then use my system preference. But then I've seen this in the docs: +resetStandardUserDefaults

有没有两个分支的默认保存在某个地方?

Are there two branches of defaults saved somewhere? The ones from the user, and the ones from the developer?

推荐答案

是的,但是它和你所使用的有点不同做。 NSUserDefaults有 registerDefaults 方法,它允许您使用您提供的值填充来自NSDictionary的空白默认值。把它放在应用控制器的+ initialize方法中,你会知道默认值是明智的。如果用户默认对象找到一个键的真实值,不管是在当前应用程序启动期间设置还是从磁盘加载,它总是优先于您在 registerDefaults resetStandardUserDefaults 将从内存中删除共享用户默认值对象,并撤消您对其进行的任何自定义,这不是您需要提供默认值。

Yes, but it's a little different than what you're doing. NSUserDefaults has the registerDefaults method, which lets you populate the "blank" defaults from an NSDictionary with values you provide. Put this in the +initialize method in your app controller, and you'll know the default values are sensible. If the user defaults object finds a "real" value for a key, either one you set during the current application launch or loaded from disk, it will always take precedent over what you provided in registerDefaults. resetStandardUserDefaults will remove the shared user defaults object from memory and undo any customization you've made to it, it's not something you'll need to provide default values.

另外,记住,你不能只是将一个对象转换为一个原始的NSInteger值,因为你在做,你会得到一个数字,代表的内存位置的对象的指针。或者使用NSUserDefault的 integerForKey:直接获取原语,或者使用 objectForKey:获取NSNumber并使用 integerValue 来获取原始值。

Also, keep in mind you can't just cast an object to a primitive NSInteger value as you're doing, you'll just end up with a number representing the memory location of the object's pointer. Either use NSUserDefault's integerForKey: to get a primitive directly, or use objectForKey: to get an NSNumber and use integerValue to get the primitive value.

这篇关于NSUserDefaults:+ resetStandardUserDefaults方法有什么好处?如何提供“系统设置”?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆