我正在使用核心数据构建一个聊天应用程序,并且有带有聊天列表的ViewController
。我每次在 View 出现之前都尝试更新此列表:
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
chatlist.removeAll()
tableView.reloadData()
guard let appDelegate = UIApplication.shared.delegate as? AppDelegate else {
return
}
let managedContext = appDelegate.persistentContainer.viewContext
let fetchRequest = NSFetchRequest<NSManagedObject>(entityName: "MessagesList")
let sort = NSSortDescriptor(key: "date", ascending: false)
fetchRequest.sortDescriptors = [sort]
do {
self.chatlist = try managedContext.fetch(fetchRequest)
} catch let error as NSError {
print("Could not fetch. \(error), \(error.userInfo)")
}
}
但它只调用一次,当我转到另一个ViewController
并返回到这个时,数据没有更新,第二次获取查询不起作用。如何在每次VC出现时从Core Data中获取数据,或者更好的是如何在VC内部更新后台数据?
最佳答案
第一个打开的表会自动重新加载,但第二个不会出现,所以请尝试 设置数组后重新加载表格,例如
self.chatlist = try managedContext.fetch(fetchRequest)
tableView.reloadData()
关于swift - 多次获取核心数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59338801/