How to programmatically control a KVC object?

I am trying to control NSMutableArray for changes through code. I want to add an observer for whenever the array changes, but I don't see what should be for the NotificationName for this to happen.

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

+4
source share
1 answer

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

Whatever object he cares about, the array registers itself as an observer:

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

He will then receive a notification 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 method will collect all the observations for which this object is registered. If you register the same object to observe many different keys, you may have to differentiate them when you call this method; that the purpose of the arguments is keyPath and object .

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

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

An arbitrary framework class will have some properties, which are some properties that do not meet the requirements of Key-Value Observing. For example, NSWindow firstResponder is firstResponder compatible, but its childWindows not. The documents, of course, will tell you which ones.

+5
source

All Articles