I'm trying to wrap my head around NSNotification but can't seem to get it to work. Think I'm misunderstanding how to register for an notification.
I have a bool as a property in my connection manager class. At initialisation I authenticate with a few servers and check if I can access an external URL (App will mainly be used on company intranet and an external connection isn't always possible)
The BOOL property will be changed from YES to NO if it cannot access the connection and as this can be responded at any time I thought it would be best to register a notification for when it changes. The property is called externalConnectionAvailable
[ConnectionManager addObserver:self forKeyPath:@"externalConnectionAvailable" options:(NSKeyVa开发者_Python百科lueObservingOptionNew | NSKeyValueObservingOptionOld) context:NULL];
and have the method:
-(void) observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context {
NSLog(@"observer called");
}
But this doesn't get called. Am I doing something completely wrong?
Thanks
In this statement:
[ConnectionManager addObserver:self forKeyPath:@"externalConnectionAvailable" options:(NSKeyValueObservingOptionNew | NSKeyValueObservingOptionOld) context:NULL];
Assuming that you are following the "Cocoa Way" and using the usual naming scheme for classes and object instances, you appear to be trying to add an observer for an entire class, as opposed to an object instance.
You should have something like
ConnectionManager *connectionManagerInstance = // initialize manager...
...
[connectionManagerInstance addObserver:self forKeyPath:@"externalConnectionAvailable" options:(NSKeyValueObservingOptionNew | NSKeyValueObservingOptionOld) context:NULL];
It was something very stupid. I was just changing the property by calling externalConnectionAvailable not self.externalConnectionAvailable
精彩评论