Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
288 views
in Technique[技术] by (71.8m points)

ios - how to defaults.removeObjectForKey("") properly swift

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

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

1 Reply

0 votes
by (71.8m points)

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...