41

When observing a value on an object using addObserver:forKeyPath:options:context:, eventually you'll want to call removeObserver:forKeyPath: on that object to clean up later. Before doing that though, is it possible to check if an object actually is observing that property?

I've tried to ensure in my code that an object is only having an observer removed when it needs to be, but there are some cases where it's possible that the observer may try to remove itself twice. I'm working to prevent this, but just in case, I've just been trying to figure out if there's a way to check first if my code actually is an observer of something.

Costique
  • 23,712
  • 4
  • 76
  • 79
Josh Buhler
  • 26,878
  • 9
  • 29
  • 45
  • KVO as it is has a rather crude API. There are libraries available that simplify its usage and even allow you to use blocks for convenience. Check out http://thirdcog.eu/pwcblocks/#goodies for details. I've also got my own implementation with the ability to automatically remove observers when either object is deallocated. It has not been tested in real applications yet, but you might want to take a look anyway. Search for `tastykvo` on GitHub. – Alexei Sholik Feb 10 '12 at 17:46
  • using a bool value like suggested in this answer worked the best for me: https://stackoverflow.com/a/37641685/4833705 – Lance Samaria Jun 11 '20 at 22:02

3 Answers3

46

[...] is it possible to check if an object actually is observing that property?

No. When dealing with KVO you should always have the following model in mind:

When establishing an observation you are responsible for removing that exact observation. An observation is identified by its context—therefore, the context has to be unique. When receiving notifications (and, in Lion, when removing the observer) you should always test for the context, not the path.

The best practice for handling observed objects is, to remove and establish the observation in the setter of the observed object:

static int fooObservanceContext;

- (void)setFoo:(Foo *)foo
{
    [_foo removeObserver:self forKeyPath:@"bar" context:&fooObservanceContext];

    _foo = foo; // or whatever ownership handling is needed.

    [foo addObserver:self forKeyPath:@"bar" options:0 context:&fooObservanceContext];
}

- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context
{
    if (context == &fooObservanceContext) {
        // handle change
    } else {
        // not my observer callback
        [super observeValueForKeyPath:keyPath ofObject:object change:change context:context];
    }
}

- (void)dealloc
{
    self.foo = nil; // removes observer
}

When using KVO you have to make sure that both objects, observer and observee, are alive as long as the observation is in place.

When adding an observation you have to balance this with exactly one removal of the same observation. Don't assume, you're the only one using KVO. Framework classes might use KVO for their own purposes, so always check for the context in the callback.

One final issue I'd like to point out: The observed property has to be KVO compliant. You can't just observe anything.

Community
  • 1
  • 1
Nikolai Ruhe
  • 81,520
  • 17
  • 180
  • 200
  • Do you need to set fooObservanceContext to anything, or is that taken care of when you add the observer? – jrturton Feb 10 '12 at 17:59
  • 2
    It is automatically initialized to zero, but in this case it is only used for its address. We need a unique value for the `context`. Since we don't know what other people use as a context, this seems to be a nice way of creating a value that is very unlikely to be used before. – Nikolai Ruhe Feb 10 '12 at 18:04
  • Ok, so it has an address because it is static, and that's what you are passing using the &? I'm not too hot on all that side of things, thanks for the explanation! – jrturton Feb 10 '12 at 18:06
  • It has an address because it is a *variable with static storage duration* (== global variable). I used the `static` *storage class modifier* to hide its symbol outside of the current compilation unit (== make it private). – Nikolai Ruhe Feb 10 '12 at 18:10
  • Thanks for that. One more question if I may - since this is a static, I understand that it is shared across all instances of the class - so are there any potential issues with multiple instances then sharing the same observation context? Would you use a different technique if that was the case? – jrturton Feb 10 '12 at 18:13
  • Not sure if this is the correct way to handle it. But instead of a `static int`, I used an `NSNumber` ivar that is initialized with `NO` at init and is set to `YES` when I set the observer. This way, I still have a unique address for that object and can remove the observer only if necessary in the `dealloc` even if I didn't set it (I just check for the `BOOL` value of my `NSNumber`). – SpacyRicochet Jul 17 '12 at 14:01
  • 2
    @SpacyRicochet Don't use the object pointer `[NSNumber numberWithBool:YES]` as a KVO context. It's not unique (frequently used NSNumbers are reused). Using the instance variable's address is safe, though. – Nikolai Ruhe Jul 17 '12 at 14:40
  • one debugging tip, we can write static NSString * kObservanceContext = "fooBarObservanceContext"; and use po *(id *)context to print contents of context in gdb. thax to http://www.dribin.org/dave/blog/archives/2008/09/24/proper_kvo_usage/ – Adeem Maqsood Basraa Nov 28 '12 at 16:25
  • How do you prevent "Cannot remove an observer <> for the key path "" from <> because it is not registered as an observer." when doing your first set? – capikaw Nov 10 '13 at 20:34
  • @capikaw By never setting the ivar directly (not even in `init`). Then we can be sure that at the first time the method is called the ivar is `nil` and the removeObserver message is ignored. – Nikolai Ruhe Nov 11 '13 at 09:40
  • Don't use the instance variable's address. A superclass or subclass would share that. Just use a static NSInteger context in the class .m and then use &context. Likewise, strings might be pooled. That's not really safe either. – Steven Fisher Apr 25 '14 at 22:42
27

Part of the NSKeyValueObserving protocol is this:

 - (void *)observationInfo

which should list the observers.

EDIT Useful for debugging only.

Rayfleck
  • 12,116
  • 8
  • 48
  • 74
  • 1
    I was just writing an answer to the effect that the list explicitly isn't available because `observationInfo` is documented to return an opaque pointer (which, indeed, may or may not be an object). Does that sound accurate? – Tommy Feb 10 '12 at 17:34
  • @Tommy Most likely it is accurate. I was just going by the doc which says "returns a pointer that identifies information about all of the observers". I suspect you understand this far more deeply than I do. – Rayfleck Feb 10 '12 at 17:42
  • 3
    You cannot use this in production code, but in the debugger it is quite useful: type `po [observedObject observationInfo]` and you get a nice overview of observers and key paths. – Nikolai Ruhe Feb 10 '12 at 17:43
1

I underestand this an objective-c question. But since lots of people use Swift/objective-c together, I thought I point out the advantage of the Swift4 new API over older versions of KVO:

If you do addObserver multiple times for KVO, then for each change you’ll get the observeValue as many as the current number of times you’ve added yourself as the observer.

  • And to remove yourself you have to call removeObserver as many times as you added.
  • Removing it more than you’ve added will result in a crash

The Swift4 observe is far smarter and swiftier!

  • If you do it multiple times, it doesn’t care. It won’t give multiple callbacks for each change.
  • And only one invalidate of the token is enough.
  • invalidating it before beginning to observer or more times that that you’ve done observe will not result in a crash

So to specifically answer your question, if you use the new Swift4 KVO, you don't need to care about it. Just call invalidate and you're good. But if you're using the older API then refer to Nikolai's answer

mfaani
  • 33,269
  • 19
  • 164
  • 293
  • Just a side note. For the `NotificationCenter`: Calling `NotificationCenter.default.removeObserver` won't be a problem if you haven't done `addObserver` yet. Also calling `addObserver` _multiple_ times will result in _multiple_ callbacks to your selector. So NotificationCenter is safe for when removing, but it's not very smart for adding. – mfaani Oct 03 '18 at 03:22