Can KVO be used to observe a global variable?

cocoa-touch, key-value-observing, objective-c

Solution

You cannot add observers for global variables, KVO only works with properties of objects. You could wrap your global variable inside a getter/setter pair on your app delegate, but then you could also use a regular property since only changes using the setter will fire KVO notifications.

Also, you should not use global variables anyways, not even if you disguise them as a 'Singleton'.

Problem

I have a gloabal variable, `User * currentUser;`, which might be changed from any class. I want to save it to `NSUserDefaults` at any change. Is it possible to use KVO for a global variable like this, or is there any other way to accomplish a similar effect? I added my app delegate as an observer for `currentUser`: ``` [self addObserver:self forKeyPath:@"currentUser" options:NSKeyValueObservingOptionNew context:nil]; ``` -- ``` -(void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context { if ([keyPath isEqualToString:@"currentUser"]) { NSDictionary * userDict = [currentUser dictionaryRepresantation]; [UserDefaults setObject:userDict forKey:@"USER_DATA"]; [UserDefaults synchronize]; } } ``` but this is not called.

Original source