user1063613
user1063613

Reputation:

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!

Upvotes: 0

Views: 2550

Answers (3)

Flavien Volken
Flavien Volken

Reputation: 21259

CRD is right, "In KVO only the property is observed, not the value" Typically dictionaries or custom objects are KVO but not the leaves (values) themselves (numbers, strings). Facing a similar problem, I finally extended the NSNumber class making it KVO compliant. Now if you are looking for different approaches to achieve notifications in your app, I would strongly suggest to read this article.

Upvotes: 0

CRD
CRD

Reputation: 53000

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.

Upvotes: 2

NSResponder
NSResponder

Reputation: 16857

The usual way to do this kind of thing is by making it a value reachable from some globally-available object, such as NSApp, or its delegate.

Upvotes: 0

Related Questions