ios - UserDefaults.didChangeNotification 未触发
问题描述
我正在处理的项目有一个将数据写入 UserDefaults 的扩展。然后在包含的应用程序中,UI 应该根据更改进行更新。问题是UserDefaults.didChangeNotification
除非屏幕来自背景,否则它不会被解雇。可能是什么原因,有没有办法修复或其他方式来获得所需的更新?
在扩展中写入数据:
let sharedUserDefaults = UserDefaults(suiteName: Common.UserDefaultsSuite)
var receivedNotifications = sharedUserDefaults?.array(forKey: Common.ReceivedNotifications)
if receivedNotifications != nil {
receivedNotifications?.append(aData)
} else {
receivedNotifications = [aData]
}
sharedUserDefaults?.set(receivedNotifications, forKey: Common.ReceivedNotifications)
在视图控制器中注册通知:
override func viewDidLoad() {
super.viewDidLoad()
NotificationCenter.default.addObserver(self, selector: #selector(userDefaultsDidChange), name: UserDefaults.didChangeNotification, object: nil)
}
并使用更改的用户默认值(实际上没有被调用):
@objc func userDefaultsDidChange(_ notification: Notification) {
print("User defaults did change")
gatherReceivedNotifications()
}
解决方案
仍然不知道为什么其他方式不起作用,但以下方法有效,所以这是一个解决方案。按照这里的建议,我做了以下事情:
override func viewDidLoad() {
super.viewDidLoad()
UserDefaults(suiteName: Common.UserDefaultsSuite)?.addObserver(self, forKeyPath: Common.ReceivedNotifications, options: .new, context: nil)
}
然后实施observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?)
:
override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) {
if keyPath == Common.ReceivedNotifications {
gatherReceivedNotifications()
}
}
它会立即触发,并且仅在对密钥的 UserDefaults 进行更改时触发Common.ReceivedNotifications
。
推荐阅读
- javascript - 状态更新时 Ant Design Range Picker 不更新日期
- r - 基于列的R滚动函数
- ruby-on-rails - 如何以及在哪里定义在控制器中使用的方法?
- angularjs - 无法使用 ng-intl-tel-input 验证巴西手机号码
- android - 如何使用导航组件从一个活动导航到另一个活动并从堆栈中删除第一个活动?
- algorithm - 在一组球体之间的间隙中找到最大球体的算法
- java - Java - 继承和多态
- jboss - 从 JBoss EAP 7.1 中排除静态 httpcomponent 模块而不排除 resteasy
- ibm-cloud - Watson Assistant API v2 和会话到期
- python - Odoo 11 开发者菜单中的“Fields view get”选项是什么?