AWF4vk
AWF4vk

Reputation: 5890

How to programmatically monitor KVC object?

I'm trying to monitor a NSMutableArray for changes via code. I want to add an observer for whenever the array changes, but I don't see what the NotificationName is supposed to be to make that happen.

Basically, when the array is modified, I want to execute a custom selector.

Upvotes: 4

Views: 1639

Answers (1)

jscs
jscs

Reputation: 64002

I'm not 100%, but I'm pretty sure that Key-Value Observing is what you want.

Whatever object it is that cares about the array registers itself as an observer:

[objectWithArray addObserver:self 
                  forKeyPath:@"theArray"
                     options:NSKeyValueObservingOptionNew 
                     context:nil];

It will then receive notice that the array has changed:

- (void)observeValueForKeyPath:(NSString *)keyPath 
                      ofObject:(id)object 
                        change:(NSDictionary *)change 
                       context:(void *)context {

    NSLog(@"Change is good: %@", [change objectForKey:NSKeyValueChangeNewKey]);
}

Note that this one method will collect all the observations that this object has registered for. If you register the same object to observe many different keys, you will likely have to differentiate them when this method gets called; that's the purpose of the keyPath and object arguments.

The problem, and the reason I'm not sure if this will work for you, is that this assumes that the array is in your code, because you need to wrap accesses to it in order for the notification to be sent.

[self willChangeValueForKey:@"theArray"];
[theArray addObject:...];
[self didChangeValueForKey:@"theArray"];

An arbitrary framework class will have some properties which are, and some properties which are not, Key-Value Observing compliant. For example, NSWindow's firstResponder is KVO compliant, but its childWindows is not. The docs, of course, will tell you which are which.

Upvotes: 5

Related Questions