在一个 View 中,我对我的核心数据数据库进行了一些更改,该数据库显示在主视图 Controller 的一个表中。进行这些更改后,我想向 reloadData()
表显示我添加的新记录,但我找不到一种方法来获取对它的引用以调用该函数。
我已经试过了:
let window = NSApplication.shared.mainWindow
我想如果我能得到窗口,我也许能得到它的 View Controller ,但由于某种原因 window
是 nil
。我觉得这应该是一件直截了当的事情,但我找不到办法去做。
如果这是不可能的,或者有更好的方法来做我正在尝试做的事情,那也会很有用。
编辑:不知道为什么,但是 NSApplication.shared.mainWindow
不再返回 nil
,但是我实际上正在对 View 窗口进行更改(不是主 ViewController
窗口)
最佳答案
我认为你应该使用 NotificationCenter,如下所示
class MainController:UIViewController {
@IBOutlet weak var tableview:UITableView!
override func viewDidLoad() {
super.viewDidLoad()
NotificationCenter.default.addObserver(self, selector: #selector(reload), name: NSNotification.Name("dataUpdated"), object: nil)
}
deinit {
NotificationCenter.default.removeObserver(self, name: NSNotification.Name("dataUpdated"), object: nil)
}
@objc func reload() {
tableview.reloadData()
}
}
使用
//cordata发生变化后,只发布通知。
NotificationCenter.default.post(name: NSNotification.Name("dataUpdated"), object: nil)
关于swift - 如何获得对主视图 Controller 的引用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50211781/