Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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".

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
275 views
Welcome To Ask or Share your Answers For Others

1 Answer

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...