quantumpotato
quantumpotato

Reputation: 9767

View Key value observations

How do I know what items my object is key-value observing?

The only way I've been able to find out if I'm already observing is to try to remove the observation. If an exception is thrown, then I wasn't observing.

for (AVPlayerItem *item in itemsToRemove) {
    @try{
        [item removeObserver:self forKeyPath:@"status" context:(__bridge void *)(foo)];
    }@catch(id anException){
        //wasn't observing
    }
}

EDIT: I'm considering using my own dictionary to track observation but that seems redundant since a KVO Dictionary does exist somewhere. Unfortunately there is no API access.

Upvotes: 0

Views: 124

Answers (2)

pronebird
pronebird

Reputation: 12260

There is no way to know that until you add some boolean flag to your controller and use it to mark and check if your registered for KVO. Normally you should balance out registration and unregistration from KVO observation.

Using exception under ARC is bad and may lead to memory leaks until you use -fobjc-arc-exceptions.

Long story short: Exceptions are expensive, that's why ARC does not properly handle them until you explicitly ask. There is an explanation to that: https://stackoverflow.com/a/4649234/351305

Upvotes: 0

Michał Ciuba
Michał Ciuba

Reputation: 7944

It seems there is no other option than catching the exception, even NSHipster recommends to do so. However, at least in my case, it was hardly ever needed to do the check. After all, you are the one who controls the observers.

You can use a wrapper (like FBKVOController) which adds more sanity to the raw KVO (and makes observing a lot easier, allowing to use blocks). Among other features, it doesn't crash when trying to remove a nonexistent observer:

 @discussion If not observing object key path, or unobserving nil, this method results in no operation.
 */
- (void)unobserve:(id)object keyPath:(NSString *)keyPath;

Upvotes: 3

Related Questions