Saving contents of UITextFiled to NSUserDefaults

有些话、适合烂在心里 提交于 2019-12-12 04:18:41

问题


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


来源:https://stackoverflow.com/questions/34802874/saving-contents-of-uitextfiled-to-nsuserdefaults

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!