如何 defaults.removeObjectForKey("") 正确 swift

how to defaults.removeObjectForKey("") properly swift

我有以下内容:

                let defaults: NSUserDefaults = NSUserDefaults.standardUserDefaults()
                let phone = defaults.objectForKey("phone") as String                   
                println(phone)       
                defaults.removeObjectForKey("phone")
                println("phone2\(phone)")

尽管尝试取消设置,打印件显示相同的结果,如“5”或“6”。

答案很简单。您正在打印先前分配的 phone 变量。您需要再次从 NSUserDefaults 中检索值以检查它是否存在。

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")
}

您正在打印变量 phoneremoveObjectForKey 不会更新变量 phone。因此,您必须从 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)")

就像@Lyndshey 所说,您不必Synchronize,因为它会定期自动发生。但是,如果您等不及要退出,您可以 Synchronize,但这确实是性能问题。

请检查Apple Documentation, and also check this Whosebug answer