问题描述
我的应用有多个通知和观察者,可在用户添加或删除数据时刷新视图。
我应该为每种类型的数据交互使用通知和观察者吗?例如:
NotificationCenter.default.post(name: NSNotification.Name(rawValue: "categoryAdded"),object: nil)
然后针对每个通知:
NotificationCenter.default.addobserver(self,selector: #selector(self.refresh),name: NSNotification.Name(rawValue: "categoryAdded"),object: nil)
NotificationCenter.default.addobserver(self,name: NSNotification.Name(rawValue: "transactionAdded"),name: NSNotification.Name(rawValue: "transactionDeleted"),name: NSNotification.Name(rawValue: "transactionEdited"),object: nil)
或者我可以只使用一个值:
NotificationCenter.default.post(name: NSNotification.Name(rawValue: "dataUpdated"),object: nil)
然后使用一个观察者:
NotificationCenter.default.addobserver(self,name: NSNotification.Name(rawValue: "dataUpdated"),object: nil)
解决方法
我认为对于您的情况,您选择使用单个值和单个观察者将是更好的选择,因为您在观察者类 (#selector(self.refresh)
) 中执行相同的操作。
您也可以考虑使用委托模式。