I have the following:
let defaults: NSUserDefaults = NSUserDefaults.standardUserDefaults()
let phone = defaults.objectForKey("phone") as String
println(phone)
defaults.removeObjectForKey("phone")
println("phone2\(phone)")
The prints are showing the same result despite attempted unset, results such as "5" or "6".
You're printing the variable phone
, removeObjectForKey
is not going to update the variable phone
. So, you've to get the updated value from NSUserdefaults
,
let defaults: NSUserDefaults = NSUserDefaults.standardUserDefaults()
defaults.setObject("Hello", forKey: "phone")
let phone = defaults.objectForKey("phone") as String
// This will save your value in `phone`
// Do not synchronize after removing the key, if you want 'value' for your key 'phone' after your application terminated
defaults.synchronize()
println(phone)
defaults.removeObjectForKey("phone")
// Get the updated value,
let updatedPhone = defaults.objectForKey("phone") as String?
// This will save nil in your `phone` key, make sure that what you want
defaults.synchronize()
println("phone2\(updatedPhone)")
Like @Lyndshey said, you don't have to Synchronize
, because it'll happen automatically at periodic intervals. But if you can't wait for it and your app is going to exit, you can Synchronize
, but really this is performance issue.
Please check Apple Documentation, and also check this Stackoverflow answer
Answer is simple. You are printing the previously assigned phone
variable. You need to again retrieve the value from NSUserDefaults
to check whether it exists or not.
let defaults: NSUserDefaults = NSUserDefaults.standardUserDefaults()
var phone = defaults.objectForKey("phone") as String
println(phone)
defaults.removeObjectForKey("phone")
if let phone = defaults.objectForKey("phone") as? String
{
println("phone2\(phone)")
}
else
{
println("Value is nil")
}