首页 > 解决方案 > 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()

}

标签: iosswiftnotificationsuserdefaults

解决方案


仍然不知道为什么其他方式不起作用,但以下方法有效,所以这是一个解决方案。按照这里的建议,我做了以下事情:

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


推荐阅读