How can i tell if an object has a key value observ

2019-01-12 16:33发布

if you tell an objective c object to removeObservers: for a key path and that key path has not been registered, it cracks the sads. like -

'Cannot remove an observer for the key path "theKeyPath" from because it is not registered as an observer.'

is there a way to determine if an object has a registered observer, so i can do this

if (object has observer){
  remove observer
}
else{
  go on my merry way
}

10条回答
叼着烟拽天下
2楼-- · 2019-01-12 17:28

[someObject observationInfo] return nil if there is no observer.

if ([tableMessage observationInfo] == nil)
{
   NSLog(@"add your observer");
}
else
{
  NSLog(@"remove your observer");

}
查看更多
Juvenile、少年°
3楼-- · 2019-01-12 17:37

Put a try catch around your removeObserver call

@try{
   [someObject removeObserver:someObserver forKeyPath:somePath];
}@catch(id anException){
   //do nothing, obviously it wasn't attached because an exception was thrown
}
查看更多
三岁会撩人
4楼-- · 2019-01-12 17:37

FWIW, [someObject observationInfo] seems to be nil if someObject doesn't have any observers. I wouldn't trust this behavior, however, as I haven't seen it documented. Also, I don't know how to read observationInfo to get specific observers.

查看更多
萌系小妹纸
5楼-- · 2019-01-12 17:38

I am not a fan of that try catch solution so what i do most of the time is that i create a subscribe and unsubscribe method for a specific notification inside that class. For example these two methods subcribe or unsubscribe the object to the global keyboard notification:

@interface ObjectA : NSObject
-(void)subscribeToKeyboardNotifications;
-(void)unsubscribeToKeyboardNotifications;
@end

Inside those methods i use a private property which is set to true or false depending on the subscription state like so:

@interface ObjectA()
@property (nonatomic,assign) BOOL subscribedToKeyboardNotification
@end

@implementation

-(void)subscribeToKeyboardNotifications {
    if (!self.subscribedToKeyboardNotification) {
        [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(onKeyboardShow:) name:UIKeyboardWillShowNotification object:nil];
        [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(onKeyboardHide:) name:UIKeyboardWillHideNotification object:nil];
        self.subscribedToKeyboardNotification = YES;
    }
}

-(void)unsubscribeToKeyboardNotifications {
    if (self.subscribedToKeyboardNotification) {
        [[NSNotificationCenter defaultCenter]removeObserver:self name:UIKeyboardWillShowNotification object:nil];
        [[NSNotificationCenter defaultCenter]removeObserver:self name:UIKeyboardWillHideNotification object:nil];
        self.subscribedToKeyboardNotification = NO;
    }
}
@end
查看更多
登录 后发表回答