KVO - How to check if an object is an observer?

31,004

Solution 1

[...] 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.

Solution 2

Part of the NSKeyValueObserving protocol is this:

 - (void *)observationInfo

which should list the observers.

EDIT Useful for debugging only.

Solution 3

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

Share:
31,004
Josh Buhler
Author by

Josh Buhler

Developer at Control4. If I'm not coding, I'm usually playing games, guitar, or out in the garage.

Updated on August 20, 2022

Comments

  • Josh Buhler
    Josh Buhler almost 2 years

    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.

  • Tommy
    Tommy over 12 years
    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?
  • Rayfleck
    Rayfleck over 12 years
    @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.
  • Nikolai Ruhe
    Nikolai Ruhe over 12 years
    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.
  • jrturton
    jrturton over 12 years
    Do you need to set fooObservanceContext to anything, or is that taken care of when you add the observer?
  • Nikolai Ruhe
    Nikolai Ruhe over 12 years
    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.
  • jrturton
    jrturton over 12 years
    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!
  • Nikolai Ruhe
    Nikolai Ruhe over 12 years
    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).
  • jrturton
    jrturton over 12 years
    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?
  • SpacyRicochet
    SpacyRicochet almost 12 years
    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).
  • Nikolai Ruhe
    Nikolai Ruhe almost 12 years
    @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.
  • Adeem Maqsood Basraa
    Adeem Maqsood Basraa over 11 years
    one debugging tip, we can write static NSString * kObservanceContext = "fooBarObservanceContext"; and use po *(id *)context to print contents of context in gdb. thax to dribin.org/dave/blog/archives/2008/09/24/proper_kvo_usage
  • capikaw
    capikaw over 10 years
    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?
  • Nikolai Ruhe
    Nikolai Ruhe over 10 years
    @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.
  • Steven Fisher
    Steven Fisher about 10 years
    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.
  • mfaani
    mfaani over 5 years
    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.