I worked on an example in the concurrency chapter "More iPhone 3 Development" and cannot get KVO on NSOperationQueue, working as expected. I create NSOperationQueueand observe its array operationsusing:
NSOperationQueue *newQueue = [[NSOperationQueue alloc] init];
self.queue = newQueue;
[newQueue release];
[queue addObserver:self
forKeyPath:@"operations"
options:(NSKeyValueObservingOptionNew | NSKeyValueObservingOptionOld)
context:NULL];
When the first one is added to the queue NSOperation, I expect it to be added to its base array operations(which the iOS documentation talks about KVO compatibility) and, therefore, in the change dictionary to find the mapping from NSKeyValueChangeKindKeyto NSKeyValueChangeInsertionas well as the mapping from NSKeyValueChangeNewKeyto added NSOperation. But I did not see any value NSKeyValueChangeInsertion.
I know that the debugger is a professional and that's it, but in the interest of having something useful for copying here, I started my observation method with:
- (void) observeValueForKeyPath:(NSString *)keyPath
ofObject:(id)object
change:(NSDictionary *)change
context:(void *)context {
NSNumber *kind = [change objectForKey:NSKeyValueChangeKindKey];
NSObject *newValue = [change objectForKey:NSKeyValueChangeNewKey];
NSObject *oldValue = [change objectForKey:NSKeyValueChangeOldKey];
NSIndexSet *indexes = [change objectForKey:NSKeyValueChangeIndexesKey];
NSLog(@"kind=%d, newValue=%@, oldValue=%@, indexes=%@",
[kind integerValue], newValue, oldValue, indexes);
And what prints:
2010-11-18 20:01:56.249 Stalled[2692:6f07] kind=1, newValue=(
"<SquareRootOperation: 0x5f51b40>"
), oldValue=(
), indexes=(null)
2010-11-18 20:01:56.250 Stalled[2692:6f07] kind=1, newValue=(
"<SquareRootOperation: 0x5f51b40>"
), oldValue=(
"<SquareRootOperation: 0x5f51b40>"
), indexes=(null)
(It SquareRootOperation’s just my subclass NSOperation, which overrides accordingly main, and Stalledjust the name of the project.) But note that the method is called twice when one operation is inserted, and both times with a value of the form 1, which NSKeyValueChangeSettingis not NSKeyValueChangeInsertion. In addition, newValuethey oldValueseem to be the array itself, and not an added element.
Any ideas? Thank!