Reputation: 354
I am using NSUserDefaults to store key/value pairs in my application. Below is the sample code:
override func viewDidAppear(animated: Bool) {
super.viewDidAppear(animated)
let ud = NSUserDefaults.standardUserDefaults()
if !(ud.boolForKey("launched_before")) {
print("first_launch")
ud.setBool(true, forKey: "launched_before")
} else {
print("not_first_launch")
}
}
The first time I launch the application, it prints "first_launch" as expected, and the second time I launch the application, it prints "not_first_launch" as expected too. However, if I continue re-launching the application by pressing Stop and Run button in the Xcode after a few times (maybe 4 to 20 times), the boolForKey("launched_before")
will return false, which is wrong.
I am testing on my device (iPhone 6, iOS 9.3.1) and Xcode 7.3.
Anyone can help me?
Upvotes: 3
Views: 219
Reputation: 3141
NSUserDefaults does save unreliably, even worse that your just terminating it through Xcode stop/run.
Calling NSUserDefaults.StandardUserDefaults().synchronize
will save the data.
Upvotes: 4