简体   繁体   中英

Saving contents of UITextFiled to NSUserDefaults

I'm trying to save a textfield and then retrieve it back in the view did load area here is my code:

@IBAction func player1button(sender: AnyObject)
{
    NSUserDefaults.standardUserDefaults().setValue(textfield1.text!, forKey:"firstPlayer")
}

override func viewDidLoad() {
    super.viewDidLoad()

    textfield1.text = (NSUserDefaults.standardUserDefaults().valueForKey("firstPlayer") as! String)
}

I'm getting this error:

terminating with uncaught exception of type NSException

使用stringForKey检索时StringNSUserDefaults

NSUserDefaults.standardUserDefaults().stringForKey("firstPlayer")

First add a target to your textField for EditingDidEnd and a method to save the textField.text property to NSUserDefault. Then you just need to load it next time your view loads (BTW you should use NSUserDefaults method stringForKey. You just need to use "??" the nil coalescing operator to provide default value in case of nil.

import UIKit

class ViewController: UIViewController {
    @IBOutlet weak var textField: UITextField!
    override func viewDidLoad() {
        super.viewDidLoad()
        textField.text = NSUserDefaults().stringForKey("textField") ?? ""
        textField.addTarget(self, action: "editingDidEnd:", forControlEvents: UIControlEvents.EditingDidEnd)
    }
    func editingDidEnd(sender:UITextField){
        NSUserDefaults().setObject(sender.text!, forKey: "textField")
    }
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM