Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can KVO be used to observe a global variable?

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.

like image 955
suleymancalik Avatar asked Oct 22 '22 17:10

suleymancalik


1 Answers

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'.

like image 177
Sven Avatar answered Nov 13 '22 01:11

Sven