Can I use KVO to monitor a global variable?

I have a useless variable User * currentUser; which can be changed from any class. I want to keep it until NSUserDefaults for any changes.

Is it possible to use KVO for a global variable like this, or is there any other way to achieve a similar effect?

I added the application 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 it is not called.

+4
source share
1 answer

You cannot add observers for global variables, KVO only works with object properties. You can wrap your global variable inside the getter / setter pair in your application, but then you can also use the regular property, since only changes using setter will trigger KVO notifications.

In addition, you should not use global variables in any way, even if you mask them as "Singleton".

+3
source

All Articles