我在一个Timer项目中,它通过展开segue从变量获取值以将其传递给另一个视图控制器,然后将其值附加到一个Array,该Array应该用于在用户按下时插入具有任务名称的行保存按钮我需要永久保存结果,但我很困惑哪些数据应该保存变量本身,行或数组的值?
var taskList = [String]()
@IBAction func saveToTaskList (segue: UIStoryboardSegue) {
let newItemViewController = segue.source as! AddTaskTableViewController
let name = newItemViewController.itemName
let date = newItemViewController.date
print("itemName passed is: \(name)")
if name == "" {
}
else {
print(date)
taskList.append(name!)
let indexToInsert = taskList.count == 0 ? 0 : taskList.count - 1
let indexPath = IndexPath(row: indexToInsert, section: 0)
tableView.insertRows(at: [indexPath], with: UITableViewRowAnimation.automatic)
}
}
答案 0 :(得分:0)
好的,感谢Matt Le Fleur的暗示 我通过使用如下对象解决了这个问题:
@IBAction func saveToTaskList (segue: UIStoryboardSegue) {
let newItemViewController = segue.source as! AddTaskTableViewController
var name = newItemViewController.itemName
let date = newItemViewController.date
let itemsObject = UserDefaults.standard.object(forKey: "items")
var items:[String]
if let tempItems = itemsObject as? [String] {
items = tempItems
items.append(name!)
print(items)
} else {
items = [name!]
}
UserDefaults.standard.set(items, forKey: "items")
name = ""
}
然后添加了一个ViewDidAppear,如下所示:
override func viewDidAppear(_ animated: Bool) {
let itemsObject = UserDefaults.standard.object(forKey: "items")
if let tempItems = itemsObject as? [String] {
items = tempItems
}
tableView.reloadData()
}