如何管理多个通知和观察者

时间:2020-10-06 15:11:54

标签: swift nsnotificationcenter observers

我的应用有多个通知和观察者,可在用户添加或删除数据时刷新视图。

我应该为每种类型的数据交互使用通知和观察者吗?例如:

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, selector: #selector(self.refresh), name: NSNotification.Name(rawValue: "transactionAdded"), object: nil)
NotificationCenter.default.addObserver(self, selector: #selector(self.refresh), name: NSNotification.Name(rawValue: "transactionDeleted"), object: nil)
NotificationCenter.default.addObserver(self, selector: #selector(self.refresh), name: NSNotification.Name(rawValue: "transactionEdited"), object: nil)

或者我可以只使用一个值:

NotificationCenter.default.post(name: NSNotification.Name(rawValue: "dataUpdated"), object: nil)

然后使用一个观察者:

NotificationCenter.default.addObserver(self, selector: #selector(self.refresh), name: NSNotification.Name(rawValue: "dataUpdated"), object: nil)

1 个答案:

答案 0 :(得分:0)

我认为对于您的情况,您选择使用单个值和单个观察者将是更好的选择,因为您在观察者类 (#selector(self.refresh)) 中执行相同的操作。

您也可以考虑使用委托模式。

相关问题