Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 816
user8472 Avatar asked Dec 28 '22 11:12

user8472


1 Answers

Yes, calling -addObserver: twice will result in two registrations. A class Foo and some subclass of Foo, Bar, may both (legitimately) register for the same notification, but with different contexts (always include the context, always check the context in -observeValueForKeyPath and always call super in -observeValueForKeyPath).

This means that an instance of Bar will register twice, and this is correct.

However, you almost certainly don't want to register the same object/keypath/context more than once accidentally, and as @wbyoung says overriding -addObserver:forKeyPath:options:context: should help you make sure this doesn't happen. If nesessary keeping track of observers/keypath/context in an array and making sure they are unique.

Mike Ash has some interesting thoughts and code on his blog about using contexts. He is right about it being broken but in practise KVO is perfectly useable.

That is, when you use it to do something it is meant todo. It used to be that you absolutely could not do something like this..

[self willChangeValueForKey:@"contents"];
[self didChangeValueForKey:@"contents"];

because it's a lie. The value of 'contents' when you call -willChange.. must be a different value from when you call -didChange... The KVO mechanism will call -valueForKey:@"contents" in both -willChangeValueForKey and -didChangeValueForKey to verify the value has changed. This obviously won't work with an array as no matter how you modify the contents you still have the same object. Now i don't know if this is still the case (a web search turned up nothing) but note that -willChangeValueForKey, -didChangeValueForKey are not the correct way to handle manual kvo of a collection. For that Apple provides alternative methods:-

– willChange:valuesAtIndexes:forKey:
– didChange:valuesAtIndexes:forKey:
– willChangeValueForKey:withSetMutation:usingObjects:
– didChangeValueForKey:withSetMutation:usingObjects:

It may not still be true that the value must change, but if it is, your scheme is not going to work.

What i would do is have one notification for modifications to your collection. And a different notification for modification of items in that collection. i.e. at the moment you are trying to trigger notifications for @"contents" when instead you could have @"contents" and @"propertiesOfContents". You would need to observe two keypaths but you can use automatic kvo instead of manually triggering the notifications. (Using automatic kvo will ensure that the correct versions of -willChange.. -didChange.. are called)

For automatic kvo of an array take a look at (no NSArrayController needed) :- Key-Value-Observing a to-many relationship in Cocoa

Then each time an item is added to the collection, observe the properties you need (as you are doing now) and when they change flip a value for self.propertiesOfContents. (ok as i read that back it doesn't necessarily sound less hacky than your solution but i still believe it may behave better).

like image 155
hooleyhoop Avatar answered Jan 26 '23 00:01

hooleyhoop