I've been struggling with registering a plist into NSUserDefaults
and I've finally got it working, though I'm not sure that its written properly. I'm hoping someone here can shine some light on this process.
My intention with this code:
I want to be able to set all of my values in a plist and essentially use that to "seed" my NSUserDefaults
. My end goal is to use this as a user settings menu.
My question:
What is the correct way to register a plist into the NSUserDefaults?
I followed the example from this this post and I received compiler errors. So I started experimenting. I could only get the code from the post to work if I added setObject(dict, forKey: "defaults")
first.
Once added, it seemed to render the registerDefaults
line pointless as the code runs with or without it.
The lines that I am questioning are these:
userDefaults.setObject(dict, forKey: "defaults") // without this my code doesn't work
userDefaults.registerDefaults(dict as! [NSObject : AnyObject]) // with or without this code works... do I need this?
I've placed the entirety of the code below to put above lines in context. This is all of the code so you can copy it right into Xcode and it will work.
ViewController.swift
class ViewController: UIViewController {
let userDefaults = NSUserDefaults.standardUserDefaults()
override func viewDidLoad() {
super.viewDidLoad()
let prefs = NSBundle.mainBundle().pathForResource("Settings", ofType: "plist")
let dict = NSDictionary(contentsOfFile: prefs!)
userDefaults.setObject(dict, forKey: "defaults") // without this code doesn't work
userDefaults.registerDefaults(dict as! [NSObject : AnyObject]) // with or without this code works... do I need this?
userDefaults.synchronize()
// this just toggles the aBool value
if let defaults = userDefaults.valueForKey("aBool") as? NSNumber {
if defaults as NSObject == 1 {
println("inside the conditional: \(defaults)")
userDefaults.setValue(0, forKey: "aBool")
userDefaults.synchronize()
println("Setting aBool to true")
} else {
userDefaults.setValue(1, forKey: "aBool")
userDefaults.synchronize()
println("setting aBool to false")
}
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
}
Settings.plist