2

Recently I read this article about observing variable changes using combine. It's working great but I like to wrap UserDefaults in another class just not to mix UserDefaults functions with my custom made ones and once I used the same code not in an extension but part of the wrapping class itself (UserDefaultsManager), the combine publisher was never executed.

class UserDefaultsManager : NSObject {
    @objc var musicVolume: Float {
        get {
            return float(forKey: "music_volume")
        }
        set {
            set(newValue, forKey: "music_volume")
        }
    }
}

...

UserDefaultsManager.shared.publisher(for: \.musicVolume) // this doesn't work now

When I move the musicVolume definition into an extension, combine publisher starts to work again:

class UserDefaultsManager : NSObject {
}
extension UserDefaultsManager {
    @objc var musicVolume: Float {
        get {
            return float(forKey: "music_volume")
        }
        set {
            set(newValue, forKey: "music_volume")
        }
    }
}

...

UserDefaultsManager.shared.publisher(for: \.musicVolume) // this works now

Anyone has an idea why it works only in extension?

I tried to look in the docs of extension and combine but I think I missed something. I will be happy to know why it's like this.

Joakim Danielson
  • 43,251
  • 5
  • 22
  • 52
gbread
  • 21
  • 1
  • 1
    I don't understand why it works when the property is in an extension but the linked duplicate question explains how to correctly using a KVO publisher by adding the `dynamic` keyword to the property declaration. – Joakim Danielson Dec 02 '22 at 12:51

0 Answers0