Swift UserDefaults返回零
试图学习做一个todolist;我有两个viewcontrollers,一个存储和一个显示在一个表视图。我的表返回零;我哪里错了?Swift UserDefaults返回零
存储视图:
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”!=“待办事项”
谢谢我没有看到 – Dev0urCode
接受它作为答案,如果这有帮助:) –
这是答案的一部分我确定但如果我只纠正错字我有一个显示错误在我的表 上述解决方案工作 – Dev0urCode
注意待办事项是小D –
工作!我必须使用stringArray,因为数据已经是数组了吗? – Dev0urCode
不,你可以使用对象,但更好地说数组字符串 –