开发者

How to get the selected value/key from PSMultiValueSpecifier?

in my Settings.bundle I have defined a PSMultiValueSpecifier. Now I want to read the selected value.

This is how I read a simple text from Settings.bundle 开发者_Go百科text field

[[NSUserDefaults standardUserDefaults] stringForKey:@"name_preference"];

Any idea how to read the selected multi value?


Using the Key you specified for this field in your Settings.plist, you can get at the selected value with:

// Assumption: myKey is a string that's equal to the Key in Settings.plist
[[NSUserDefaults standardUserDefaults] objectForKey:myKey];

There is no way to get at the title of the selected field through user defaults. You would have to read in the Settings.plist directly or store the titles and their accompanying values in a second plist in your app bundle for easy access.


Use this to get your value:

NSString* value = [[NSUserDefaults standardUserDefaults] stringForKey:@"key"] 

Key is the name of the setting you want to get the value of. You can then get float or int value of the string if you need to.


Please check the question

The code [[NSUserDefaults standardUserDefaults] stringForKey:@"key"] returns nil until data is saved to UserDefaults or user selects option manually in settings.

I suggest saving default values as selected when app launches:

static func registerSettingsDefaults()
{
    // Get Settings bundle path
    guard let settingsBundle = Bundle.main.path(forResource: "Settings", ofType: "bundle") else {
        assertionFailure("Could not find Settings bundle")
        return
    }

    // Get settings plist
    let settings = NSDictionary(contentsOfFile: settingsBundle + "/Root.plist")

    // Get preferences dictionary
    guard let preferences = settings?.object(forKey: "PreferenceSpecifiers") as? [[String: Any]] else {
        assertionFailure("Could not find preferences")
        return
    }

    // Filter out default values from Settings
    var defaultsToRegister: [String: Any] = [:]
    preferences.forEach { dictionary in
        if let key = dictionary["Key"] as? String {
            defaultsToRegister[key] = dictionary["DefaultValue"] as? String
        }
    }

    UserDefaults.standard.register(defaults: defaultsToRegister)
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜