UserDefaults不显示数据?

时间:2016-02-11 12:38:34

标签: ios swift nsuserdefaults

我正在使用一些文本字段和按钮呈现视图,用户可以在该文本字段中输入一些数据,当用户单击保存按钮时,数据将保存在NSUserdefaults中,并在另一个视图中显示,但不能正常工作..任何建议PLZ ..

  

View2代码通过view1呈现

//The default key value
var _billingAddress = "billingAddress"

//The address text field in present view
@IBOutlet weak var address: UITextField!


//The button action code
 @IBAction func saveBtn(sender: AnyObject) {

    let defaults = NSUserDefaults.standardUserDefaults()
    defaults.setValue(address.text, forKey:_billingAddress)

 }
  

View1代码访问键值数据

//Label where i want to show the saved value
@IBOutlet weak var billingAddresh: UILabel!

    let defaults = NSUserDefaults.standardUserDefaults()
    if let name = defaults.stringForKey(_billingAddress)
        //Here it shows the error use of unresolved identifier _billingAddress
    {
        billingAddresh.text = name
    }

它没有显示任何价值 谢谢你的帮助..

1 个答案:

答案 0 :(得分:0)

当您添加时,我们需要defaults.synchronize()

let defaults = NSUserDefaults.standardUserDefaults()
defaults.setValue(address.text, forKey:"billingAddress")

// if you want use else ignore 
defaults.synchronize()

检索是

let defaults = NSUserDefaults.standardUserDefaults()
if let name = defaults.stringForKey("billingAddress") // not "_billingAddress"
{
    billingAddresh.text = name
}

// no need in here 
defaults.synchronize()