Registering a bool for a NSNotification

二次信任 提交于 2019-12-13 05:16:30

问题


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


回答1:


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];



回答2:


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



来源:https://stackoverflow.com/questions/3226036/registering-a-bool-for-a-nsnotification

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!