NSUserDefaults: What's the +resetStandardUserDefaults method good for? How can I provide “system settings”?

大憨熊 提交于 2019-12-11 01:18:06

问题


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"];

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?


回答1:


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.

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.



来源:https://stackoverflow.com/questions/898301/nsuserdefaults-whats-the-resetstandarduserdefaults-method-good-for-how-can-i

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!