用户默认无法正常工作

时间:2016-12-05 07:27:17

标签: ios swift xcode swift3 nsuserdefaults

有人可以帮助我,为什么我无法正确执行 nsuserdefaults 。当我尝试点击保存它什么也没做。我想要的是当我点击保存它将保存到手机然后当我再次尝试回到视图控制器时它会出现。这是我的代码如下。

override func viewDidLoad() {
    super.viewDidLoad()

    self.navigationItem.setHidesBackButton(true, animated: false)
    self.hideKeyboardWhenTappedAround()

    firstName.delegate = self
    lastName.delegate = self

    tableView.reloadData()

    //Save Defaults
    let defaults = UserDefaults.standard
    if let _ = defaults.object(forKey: "firstName") as? String {
        self.firstName.text = defaults.object(forKey: "firstName") as? String
    }

    if let _ = defaults.object(forKey: "lastName") as? String {
        self.lastName.text = defaults.object(forKey: "lastName") as? String
    }

    if let _ = defaults.object(forKey: "contacts") as? Array<Any> {
        self.contacts = (defaults.object(forKey: "contacts") as? Array)!
    }
}



 //MARK -> SAVE BUTTON
    @IBAction func saveButtonSelected(_ sender: AnyObject) {
            let defaults: UserDefaults = UserDefaults.standard
            defaults.set(self.firstName.text, forKey: "firstName")
            defaults.set(self.lastName.text, forKey: "lastName")
            defaults.set(contacts, forKey: "contacts")
        }

0 个答案:

没有答案