Swift UserDefaults returns 无
Swift UserDefaults returns nil
努力学习做一个待办事项列表;我有两个视图控制器,一个用于存储,一个用于在 table 视图中显示。我的 table returns 无;我哪里错了?
存储视图:
var toDoStorage = UserDefaults.standard.object(forKey: "toDo")
var toDoList = [String] ()
@IBAction func saveButton(_ sender: Any) {
if (toDoStorage as? [String]) != nil {
toDoList.append(itemLabel.text!)
} else {
toDoList = [itemLabel.text!]
}
UserDefaults.standard.set(toDoList, forKey: "todo")
itemLabel.text = ""
}
显示视图:
var toDo = [UserDefaults.standard.object(forKey: "toDo")]
public func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int{
return toDo.count
}
public func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = UITableViewCell(style: UITableViewCellStyle.default, reuseIdentifier: "IDCell")
cell.textLabel?.text = String(describing: toDo[indexPath.row])
return cell
}
只需使用它来存储字符串数组
var toDo = UserDefaults.standard.stringArray(forKey: "todo") ?? [String]()
确保您的密钥匹配..
您在密钥中打错了字.. "todo" != "toDo"
努力学习做一个待办事项列表;我有两个视图控制器,一个用于存储,一个用于在 table 视图中显示。我的 table returns 无;我哪里错了?
存储视图:
var toDoStorage = UserDefaults.standard.object(forKey: "toDo")
var toDoList = [String] ()
@IBAction func saveButton(_ sender: Any) {
if (toDoStorage as? [String]) != nil {
toDoList.append(itemLabel.text!)
} else {
toDoList = [itemLabel.text!]
}
UserDefaults.standard.set(toDoList, forKey: "todo")
itemLabel.text = ""
}
显示视图:
var toDo = [UserDefaults.standard.object(forKey: "toDo")]
public func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int{
return toDo.count
}
public func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = UITableViewCell(style: UITableViewCellStyle.default, reuseIdentifier: "IDCell")
cell.textLabel?.text = String(describing: toDo[indexPath.row])
return cell
}
只需使用它来存储字符串数组
var toDo = UserDefaults.standard.stringArray(forKey: "todo") ?? [String]()
确保您的密钥匹配.. 您在密钥中打错了字.. "todo" != "toDo"