Saving contents of UITextFiled to NSUserDefaults

2019-09-09 03:31发布

问题:

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

回答1:

Use stringForKey when retrieving a String from NSUserDefaults:

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


回答2:

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