sindresorhus / Defaults

💾 Swifty and modern UserDefaults
https://swiftpackageindex.com/sindresorhus/Defaults/documentation/defaults
MIT License
1.97k stars 117 forks source link

Defaults.observe worked with UserDefaults value changes on macOS but not on iOS #107

Closed owenzhao closed 2 years ago

owenzhao commented 2 years ago

I used iCloud Key-Value sync together with Defaults.

private func syncKeyValue(_ userInfo:[String : Any]) {
    if let changedKeys = userInfo[NSUbiquitousKeyValueStoreChangedKeysKey] as? [String] {
        let store = NSUbiquitousKeyValueStore.default
        let defaults = UserDefaults(suiteName: Defaults.sharedSuitName)!

        for key in changedKeys {
            if let value = store.object(forKey: key) {
                defaults.set(value, forKey: key)
            }
        }
    }
}

And I used Defaults.observe to updated UI.

init(_ collectionView:NSCollectionView) {
    Defaults.observe(.accounts) { _ in
        collectionView.reloadData()
    }.tieToLifetime(of: self)

    Defaults.observe(.identities) { _ in
        collectionView.reloadData()
    }.tieToLifetime(of: self)
}

Above code worked on macOS. However, on iOS the UI would never be triggered when defaults.set(value, forKey: key) called. I had to manually call Defaults to trigger.

private func syncKeyValue(_ userInfo:[String : Any]) {
    if let changedKeys = userInfo[NSUbiquitousKeyValueStoreChangedKeysKey] as? [String] {
        let store = NSUbiquitousKeyValueStore.default

        for key in changedKeys {
            if let value = store.object(forKey: key) {
                switch key {
                case Defaults.Keys.accounts.name:
                    Defaults[.accounts] = value as! Data
                default:
                    break
                }
            }
        }
    }
}

As Defaults didn't allow Any. In the way, I had to specify each key in switch-case. Any idea?

sindresorhus commented 2 years ago

I doubt this is an issue with Defaults as the observation code is the same for macOS and iOS. However, submitting a failing test would be very helpful.

owenzhao commented 2 years ago

I created a new project but I couldn't reproduce this issue. So I now close this issue.