observeValue在UserDefaults

时间:2017-07-23 15:21:44

标签: ios swift key-value-observing

我的主视图控制器被添加为UserDefault中某些键的观察者。但每次更改值时,observeValue都会被调用两次。

这两个电话的堆栈不同。

第一个来自 frame #6: forEachObserver + 332 frame #7: -[CFPrefsSource didChangeValues:forKeys:count:] + 68 frame #8: -[CFPrefsSource setValues:forKeys:count:removeValuesForKeys:count:] + 340 frame #9: -[CFPrefsSource setValue:forKey:] + 56

第二个来自 frame #6: forEachObserver + 332 frame #7: -[CFPrefsSource _notifyObserversOfChangeFromValuesForKeys:toValuesForKeys:] + 68 frame #8: __84-[CFPrefsSearchListSource asynchronouslyNotifyOfChangesFromDictionary:toDictionary:]_block_invoke_2 + 36

我找到的唯一相关帖子来自cocoa-dev邮件列表https://lists.apple.com/archives/cocoa-dev/2016/Nov/msg00084.html。似乎这个问题出现在MacOS 10.12

有人可以提供有关其发生原因或如何抑制重复邮件的详细信息吗?

重现的最小例子:

import UIKit

class ViewController: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.
        UserDefaults.standard.addObserver(
            self,
            forKeyPath: "test",
            options: .new,
            context: nil
        )

        UserDefaults.standard.set(true, forKey: "test")
    }

    override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) {
        print("Observed: \(object ?? "None")")
    }
}

0 个答案:

没有答案