Multivalue type settings bundle fields alway return null

烈酒焚心 提交于 2019-11-27 15:13:09
Matthias Bauch

If the value wasn't changed by the user in the settings app there is no setting. The default value specified in the settings bundle is only the default for display in the settings app

you have to manually register your default values. NSUserdefaults doesn't use the defaults from the settings bundle.
Use something like this, add it at the beginning of your app (before you access the userdefaults).
Registered Userdefaults are not saved to disk or anything. You have to register them every time you start the app.

NSDictionary *userDefaultsDefaults = [NSDictionary dictionaryWithObjectsAndKeys:
                                      @"15", @"upthreshold",
                                      nil];
[[NSUserDefaults standardUserDefaults] registerDefaults:userDefaultsDefaults];

I just ran into this problem and I ask myself why the settings bundle provides a default value, if this value can never be read from the NSUserDefaults.

I created a swift extension that does the following:

  • Read the value for a given key
  • If the key does not exist set a default and return this default

So I can do this:

NSUserDefaults.standardUserDefaults().settignsStringValue("MYPREFS_DOMAIN", defaultValue: "domain.com")

This is the extension:

extension NSUserDefaults{

    func settingsBoolValue(key: String, defaultValue: Bool) -> Bool{
        // The case for Bool is different as it would return `false` when the key is not set.
        if let v: AnyObject = self.objectForKey(key){
            // The boolean value exists
        } else {
            self.setObject(defaultValue, forKey: key)
        }

        return self.boolForKey(key)
    }

    func settingsStringValue(key: String, defaultValue: String) -> String{
        if let v = self.stringForKey(key){
            return v
        } else {
            self.setObject(defaultValue, forKey: key)
            return defaultValue
        }
    }
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!