Search code examples
objective-ckey-value-observing

KVO: observing global NSNumber


I have static global NSNumber value and i need to observe it. If it was member of some object, i would have no problems whatsoever. But what do i do with global scope? I guess i could use

[globalVar addObserver:self forKeyPath:**integerValue** options:... ]

but that seems ugly because i might as well use "intValue" KeyPath and i need to observe NSNumber, not it's int part, even if it's the only part of it i''m using now. Making this particular variable part of some class doesn't seem like a "right" think to do. Thanks!


Solution

  • Easy answer: you can't. Observing is a software mechanism which fundamentally involves method calls, doing a store (i.e. a machine instruction) into a global variable provides no hook to hang the mechanism on.

    The best option is to re-think your design. Think of storing the value in a singleton class and accessing/observing it there.

    Hard answer: write your own mutable version of NSNumber (an instance of which is immutable) and have this class implement the key-value observing protocol (this class might just be a wrapper with an NSNumber instance variable). Now store and instance of this class in your global variable and add any observers you like to it.