5

In an effort to prevent multiple observers from being added, I'm removing the observer before I add one, which was recommended here: iPhone - testing if a notification exists.

[[self getPlayer] removeObserver:self forKeyPath:@"position"];
[[self getPlayer] addObserver:self forKeyPath:@"position" options:NSKeyValueObservingOptionNew context:nil];

However, doing so causes an exception: __CFRUNLOOP_IS_CALLING_OUT_TO_AN_OBSERVER_CALLBACK_FUNCTION__

Any ideas on how to check if an observer already exists for a key path and if so not add a new one?

Community
  • 1
  • 1
stewart715
  • 5,557
  • 11
  • 47
  • 80
  • 1
    possible duplicate of [How can i tell if an object has a key value observer attached](http://stackoverflow.com/questions/1582383/how-can-i-tell-if-an-object-has-a-key-value-observer-attached) – jscs Dec 29 '13 at 03:36

1 Answers1

7

Add a boolean that keeps track of whether or not you've added your observer. Set it to true after adding, and only remove your observer if the flag indicates that you have added one.

Duncan C
  • 128,072
  • 22
  • 173
  • 272
  • Yeah, that's the solution I'm using now, but wondering if there's a better practice for something like this. If not I'll stick to the bool. – stewart715 Dec 29 '13 at 02:44
  • Accepting this but http://stackoverflow.com/questions/1582383/how-can-i-tell-if-an-object-has-a-key-value-observer-attached seems to be the most appropriate solution. – stewart715 Dec 29 '13 at 16:27
  • 1
    Using try/catch? That's not reliable in release builds. Cocoa swallows exceptions much of the time. – Duncan C May 11 '15 at 10:44
  • anybody know if using the bool method is still the best approach? – MikeG Apr 28 '16 at 18:04