首页 > 解决方案 > 如何管理多个通知和观察者

问题描述

当用户添加或删除数据时,我的应用程序有几个通知和观察者来刷新视图。

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

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)

标签: swiftnsnotificationcenterobservers

解决方案


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

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


推荐阅读