我正在关注如何使用CoreData创建待办事项列表的YouTube教程,而我的应用程序可以构建和运行,而不是使用其他视图控制器来创建任务,我创建了一个模态视图控制器以显示在常规视图控制器。问题是它将它保存到CoreData但仅在应用程序重置时显示,这是用于常规视图控制器的所有代码,其中应显示任务:
class ViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {
@IBOutlet weak var tableViewTest: UITableView!
var tasks : [Task] = []
override func viewDidLoad() {
super.viewDidLoad()
tableViewTest.dataSource = self
tableViewTest.delegate = self
self.navigationController?.isNavigationBarHidden = true
}
override func viewWillAppear(_ animated: Bool) {
getData()
tableViewTest.reloadData()
}
func tableView(_ tableViewTest: UITableView, numberOfRowsInSection section: Int) -> Int {
return tasks.count
}
func tableView(_ tableViewTest: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = UITableViewCell()
let task = tasks[indexPath.row]
cell.textLabel?.text = task.name!
return cell
}
func getData() {
let context = (UIApplication.shared.delegate as! AppDelegate).persistentContainer.viewContext
do {
tasks = try context.fetch(Task.fetchRequest())
}
catch {
print("Fetch Error")
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
}
这是模态视图控制器的代码,用户输入的是要保存到CoreData的信息:
class popVCAdd: UIViewController {
@IBOutlet weak var textField: UITextField!
@IBOutlet weak var popViewAc: UIView!
override func viewDidLoad() {
super.viewDidLoad()
popViewAc.layer.cornerRadius = 20
popViewAc.layer.masksToBounds = true
let toolbar = UIToolbar()
toolbar.sizeToFit()
textField.inputAccessoryView = toolbar
let keyboardDone = UIBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem.done, target: self, action: #selector(self.disappearKey))
toolbar.setItems([keyboardDone], animated: false)
}
@IBAction func doneBtn(_ sender: Any) {
let context = (UIApplication.shared.delegate as! AppDelegate).persistentContainer.viewContext
let task = Task(context: context)
task.name = textField.text!
(UIApplication.shared.delegate as! AppDelegate).saveContext()
}
@IBAction func dismissPop(_ sender: Any) {
dismiss(animated: true, completion: nil)
}
func disappearKey() {
view.endEditing(true)
}
}
有人知道它有什么问题吗?