In my app, I want to use KVO to update UI when an update sent by my server is retrieved by the app. For that, I have a singleton class called "AutomaticRefreshProcess", which polls the server every second, and, if there is a new update, store it in a property lastUpdate. I want this very property to be observable by any object of my app if they need (a UIView, a UIViewController but also maybe by business model NSObject for example)
I saw (at least empirically) that the keyPath when you add an observer couldn't have any of its "node" being a static variable. So I can't do, in my observers :
addObserver(self, forKeyPath:#keyPath(AutomaticRefreshProcess.lastUpdate), options: [.new], context: nil)
I tried, this make the app crash. What I can do is, for all my observers, declare a property set at init to AutomaticRefreshProcess.lastUpdate. I tried, it works.
class MyObserver : NSObject {
@objc dynamic let lastUpdate = AutomaticRefreshProcess.lastUpdate
init()
{
addObserver(self, #keyPath(lastUpdate), ...)
}
}
This works well but, I find it redundant. Plus, I want to customize observeValue raw function to override it by a convenient more specific function to handle these updates, like :
override observeUpdate(newUpdates:[Update], ofType: UpdateType) { ... }
For that, I can create a class ARPObserver, and subclassing all the observers from it. The thing is, how can I make all the UIKit object "conforming" to this parent class, at once ? I don't want to rewrite every UIKit object to make it "ARPOberser" like UIViewARPObserver, UIViewControllerARPObserver etc.
So my question is : is there a better design pattern than subclassing all UIView, UIViewController, and so on to make all UIKit object as ARP Observers ? I would have loved to use extensions but you can't store props there, and I need to store arpInstance to make it available in the keyPath of addObserver