Returning the value of a settings bundle switch in

2019-08-05 09:30发布

I have difficulties returning the value of a stored boolean key.

My root.plist looks like this:

enter image description here

I've got this in AppDelegate:

    let a = NSUserDefaults.standardUserDefaults().boolForKey("sound")

    if a { // This is where it breaks
        println("sound is on")
    }

Any ideas what I'm doing wrong?

标签: xcode swift ios8
2条回答
唯我独甜
2楼-- · 2019-08-05 09:49

Use this:

    var myDict: NSDictionary?
// Read from the Configuration plist the data to make the state of the object valid.
    if let path = NSBundle.mainBundle().pathForResource("root", ofType: "plist") {
        myDict = NSDictionary(contentsOfFile: path)
    }

    // Set the values to init the object
    if let dict = myDict {
        if let a = dict["sound"] as? Bool {
         if a { 
            println("sound is on")
          }
        }
    }
查看更多
Summer. ? 凉城
3楼-- · 2019-08-05 09:55

First you should register your defaults so everything is sync'd up and defaults are assigned. Then you'll know a value exists. These values are not automatically synchronized on startup.

var appDefaults = Dictionary<String, AnyObject>()
appDefaults["sound"] = false
NSUserDefaults.standardUserDefaults().registerDefaults(appDefaults)
NSUserDefaults.standardUserDefaults().synchronize()

let a = NSUserDefaults.standardUserDefaults().boolForKey("sound")

if a { // This is where it breaks
    println("sound is on")
}

Below is an excerpt from a relevant article.

When Your App Uses a Settings Bundle

Keep in mind that you should also use registerDefaults: when your app uses a Settings Bundle. Since you already specified default values inside the settings bundle’s plist, you may expect that your app picks these up automatically. However, that is not the case. The information contained in the settings bundle is only read by the iOS Settings.app and never by your app. In order to have your app use the same defaults as shown inside the Settings.app, you have to manually copy the user defaults keys and their default values into a separate plist file and register it with the defaults database as shown above.

And HERE is the relevant discussion directly from Apple.

Registering Defaults

Discussion

If there is no registration domain, one is created using the specified dictionary, and NSRegistrationDomain is added to the end of the search list. The contents of the registration domain are not written to disk; you need to call this method each time your application starts. You can place a plist file in the application's Resources directory and call registerDefaults: with the contents that you read in from that file.

查看更多
登录 后发表回答