SwiftyUserDefaults icon indicating copy to clipboard operation
SwiftyUserDefaults copied to clipboard

kvo not work

Open pmlican opened this issue 1 year ago • 1 comments

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") }
 
}

pmlican avatar Jun 21 '23 06:06 pmlican

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.

developforapple avatar Sep 26 '23 02:09 developforapple