views:

62

answers:

2

Hi everyone,

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:(NSKeyValueObservingOptionNew | 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

A: 

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];
Alex Reynolds
Is there a good reason this was voted down?
Alex Reynolds
Wasn't me, ConnectionManager is actually the class thats creating it, so technically is should be self if anything, but I doubt it will work. Sorry, was very tired
Rudiger
So are you saying that I can only have a KVO on an object instance? Why not a property within a class?
Rudiger
A: 

It was something very stupid. I was just changing the property by calling externalConnectionAvailable not self.externalConnectionAvailable

Rudiger