0

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

Chris Hanson
  • 54,380
  • 8
  • 73
  • 102
Rudiger
  • 6,749
  • 13
  • 51
  • 102
  • Is ConnectionManager an instance or a class? We usually start variable names with lowercase letter. Please add the code that actually changes the value, and your value getter and setter if not synthesized. – tonklon Jul 12 '10 at 07:08
  • ConnectionManager is the class that its in, not sure why I used it, couldn't think of anything else. Should actually be self if anything – Rudiger Jul 12 '10 at 07:44

2 Answers2

0

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
  • 95,983
  • 54
  • 240
  • 345
  • 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 Jul 12 '10 at 07:49
  • So are you saying that I can only have a KVO on an object instance? Why not a property within a class? – Rudiger Jul 12 '10 at 23:21
0

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

Rudiger
  • 6,749
  • 13
  • 51
  • 102