SwiftyUserDefaults
SwiftyUserDefaults copied to clipboard
kvo not work
here my example,when click button change usename observe not work, is anything i miss?
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
Defaults.observe(\.username, options: [.initial, .old, .new]) { update in
print(update)
}
}
@IBAction func click(_ sender: Any) {
let num = Int.random(in: 0..<10)
let username = Defaults[\.username]
Defaults[\.username] = " abc \(num)"
}
}
extension DefaultsKeys {
var username: DefaultsKey<String> { .init("username", defaultValue: "default") }
}
The DefaultsDisposable instance is released, so you can't keep observing. It should be a storage property of the ViewController to prevent it from being released.