gpt4 book ai didi

xcode - Swift 2.0 版本下的 NSUserDefaults 错误

转载 作者:行者123 更新时间:2023-11-30 10:06:18 24 4
gpt4 key购买 nike

我在 Swift 2.0 版中实现 NSUserDefaults 时遇到一些问题。我的代码在 Swift v1 上工作正常,但在 v2 上有一些问题。首先,一旦我按下保存按钮,数据就不会保存,第二,一旦我按下保存按钮,我的应用程序就会崩溃。谁能告诉我我的编码做错了什么?

import UIKit

class MainTableViewController: UITableViewController, UITextFieldDelegate {

@IBOutlet weak var name: UITextField!
@IBOutlet weak var phone: UITextField!
@IBOutlet weak var email: UITextField!

@IBAction func btnSave() {

if name.text == " " {
let alert = UIAlertController(title: "Data", message: "Missing Name.", preferredStyle: UIAlertControllerStyle.Alert)
alert.addAction(UIAlertAction(title: "OK", style: UIAlertActionStyle.Default, handler: nil))
self.presentViewController(alert, animated: true, completion: nil)
}

else if phone.text == " " {
let alert = UIAlertController(title: "Data", message: "Missing Phone Number.", preferredStyle: UIAlertControllerStyle.Alert)
alert.addAction(UIAlertAction(title: "OK", style: UIAlertActionStyle.Default, handler: nil))
self.presentViewController(alert, animated: true, completion: nil)
return
}

else if email.text == " " {
let alert = UIAlertController(title: "Data", message: "Missing Email Address.", preferredStyle: UIAlertControllerStyle.Alert)
alert.addAction(UIAlertAction(title: "OK", style: UIAlertActionStyle.Default, handler: nil))
self.presentViewController(alert, animated: true, completion: nil)
return
}

let userDefaults = NSUserDefaults.standardUserDefaults()

userDefaults.setObject(name, forKey:"name")
userDefaults.setObject(phone, forKey:"phone")
userDefaults.setObject(email, forKey:"email")

userDefaults.synchronize()
}

override func viewDidLoad() {

let userDefaults = NSUserDefaults.standardUserDefaults()

userDefaults.setObject(" ", forKey: "name")
userDefaults.setObject(" ", forKey: "phone")
userDefaults.setObject(" ", forKey: "email")

super.viewDidLoad()

}
}

最佳答案

我看到您的 UITextfield 问题已解决。现在尝试以下方法来帮助您获取从 viewDidLoad 函数中保留的信息:

override func viewDidLoad() {
super.viewDidLoad()

let userDefaults = NSUserDefaults.standardUserDefaults()

if let nameSaved = userDefaults.objectForKey("name") as? String {
name.text = nameSaved
}

if let phoneSaved = userDefaults.objectForKey("phone") as? String {
phone.text = phoneSaved
}

if let emailSaved = userDefaults.objectForKey("email") as? String {
email.text = emailSaved
}
}

如果您希望每次移回 Controller 后调用它,请将其放入 viewWillAppear() 中。

关于xcode - Swift 2.0 版本下的 NSUserDefaults 错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35777104/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com