swift - 如何管理多个通知和观察者
问题描述
当用户添加或删除数据时,我的应用程序有几个通知和观察者来刷新视图。
我应该为每种类型的数据交互使用通知和观察者吗?例如:
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)
解决方案
我认为对于您的情况,您选择使用单个值和单个观察者将是更好的选择,因为您在观察者类(#selector(self.refresh)
)中做同样的事情。
您也可以考虑使用委托模式。
推荐阅读
- go - 匿名结构作为模板中的管道
- c# - 多个类之间共享的列表
- powershell - 输出一个字符串然后做一些事情并添加到同一个字符串
- android - SharedPreferences 变量只被接收并且可以在第二次执行时显示
- python - 如果响应获得带有或不带有表单的视图,我如何检查测试?
- javascript - flatpickr 不显示日历 -
- fortran - Fortran OpenMP 代码中的缩放不良和分段错误
- excel - 将 Excel 范围作为图片粘贴到电子邮件正文中
- arduino - 在静态成员函数中无效使用成员 - arduino
- php - 在 PHP foreach 中未正确关闭 XML 标记