objective-ccocoakeykey-value-observing

How can I tell if an object has a key value observer attached


If you tell an Objective-C object to removeObservers: for a key path and that key path has not been registered, it cracks a sad, like:

Cannot remove an observer <observerObject> for the key path "theKeyPath" from <objectbeingObserved> 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
}

Solution

  • 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
    }