Search code examples
iphoneobjective-ccocoa-touchkey-value-observing

How to debug KVO


In my program I use KVO manually to observe changes to values of object properties. I receive an EXC_BAD_ACCESS signal at the following line of code inside a custom setter:

[self willChangeValueForKey:@"mykey"];

The weird thing is that this happens when a factory method calls the custom setter and there should not be any observers around. I do not know how to debug this situation.

Update: The way to list all registered observers is observationInfo. It turned out that there was indeed an object listed that points to an invalid address. However, I have no idea at all how it got there.

Update 2: Apparently, the same object and method callback can be registered several times for a given object - resulting in identical entries in the observed object's observationInfo. When removing the registration only one of these entries is removed. This behavior is a little counter-intuitive (and it certainly is a bug in my program to add multiple entries at all), but this does not explain how spurious observers can mysteriously show up in freshly allocated objects (unless there is some caching/reuse going on that I am unaware of).

Modified question: How can I figure out WHERE and WHEN an object got registered as an observer?

Update 3: Specific sample code.

ContentObj is a class that has a dictionary as a property named mykey. It overrides:

+ (BOOL)automaticallyNotifiesObserversForKey:(NSString *)theKey {
    BOOL automatic = NO;
    if ([theKey isEqualToString:@"mykey"]) {
        automatic = NO;
    } else {
        automatic=[super automaticallyNotifiesObserversForKey:theKey];
    }
    return automatic;
}

A couple of properties have getters and setters as follows:

- (CGFloat)value {
    return [[[self mykey] objectForKey:@"value"] floatValue];
}
- (void)setValue:(CGFloat)aValue {
    [self willChangeValueForKey:@"mykey"];
    [[self mykey] setObject:[NSNumber numberWithFloat:aValue]
                     forKey:@"value"];
    [self didChangeValueForKey:@"mykey"];
}

The container class has a property contents of class NSMutableArray which holds instances of class ContentObj. It has a couple of methods that manually handle registrations:

+ (BOOL)automaticallyNotifiesObserversForKey:(NSString *)theKey {
    BOOL automatic = NO;
    if ([theKey isEqualToString:@"contents"]) {
        automatic = NO;
    } else {
        automatic=[super automaticallyNotifiesObserversForKey:theKey];
    }
    return automatic;
}

- (void)observeContent:(ContentObj *)cObj {
    [cObj addObserver:self
           forKeyPath:@"mykey"
              options:0
              context:NULL];
}

- (void)removeObserveContent:(ContentObj *)cObj {
    [cObj removeObserver:self
              forKeyPath:@"mykey"];
}

- (void)observeValueForKeyPath:(NSString *)keyPath
                      ofObject:(id)object
                        change:(NSDictionary *)change
                       context:(void *)context {
    if (([keyPath isEqualToString:@"mykey"]) &&
        ([object isKindOfClass:[ContentObj class]])) {
        [self willChangeValueForKey:@"contents"];
        [self didChangeValueForKey:@"contents"];
    }
}

There are several methods in the container class that modify contents. They look as follows:

- (void)addContent:(ContentObj *)cObj {
    [self willChangeValueForKey:@"contents"];
    [self observeDatum:cObj];
    [[self contents] addObject:cObj];
    [self didChangeValueForKey:@"contents"];
}

And a couple of others that provide similar functionality to the array. They all work by adding/removing themselves as observers. Obviously, anything that results in multiple registrations is a bug and could sit somewhere hidden in these methods.

My question targets strategies on how to debug this kind of situation. Alternatively, please feel free to provide an alternative strategy for implementing this kind of notification/observer pattern.

Update 4: I found the bug using a mixture of breakpoints, NSLogs, code reviews and sweating. I did not use the context in KVO, although this is definitely another useful suggestion. It was indeed a wrong double registration that - for reasons beyond my comprehension - resulted in the observed behavior.

The implementation including [self willChange...]; [self didChange...] works as described (on iOS 5), although it is far from beautiful. The issue is that as NSArray is not KVO-compliant there is no way to talk about changes to its contents. I had also thought about notifications as suggested by Mike Ash, but I decided to go with KVO as this seemed like a more Cocoa-ish mechanism to do the work. This was arguably not the best of decisions ...


Solution

  • In response to your modified question, try overriding addObserver:forKeyPath:options:context: in your custom class and setting a breakpoint on it. Alternatively, you can just set a symbolic breakpoint on -[NSObject addObserver:forKeyPath:options:context:], but that will probably get hit a lot.