yourfriendzak yourfriendzak - 2 months ago 12
iOS Question

How do I observe the "operations" property of NSOperationQueue?

I want to be notified whenever a NSOperation has been added or removed from my NSOperationQueue. I'm trying to set up key-value observing for the "operations" property (an array of NSOperations currently in the Queue) but its not being fired. Is there something wrong with my syntax?

@implementation myOperationQueueSubclass

-(id)init
{
if (self = [super init])
{
// Initialization code here
[self addObserver:self
forKeyPath:@"operations"
options:0
context:nil];

}
return self;
}

- (void)observeValueForKeyPath:(NSString *)keyPath
ofObject:(id)object
change:(NSDictionary *)change
context:(void *)context {
NSLog(@"queue changed...");
if ([keyPath isEqualToString:@"operations"]) {

if (self.operationCount == 0) {
// No ops

} else {
// Has ops
}
}
}

Answer

There's nothing wrong with your syntax, but you're observing the array property, not the array itself (which doesn't issue KVO notifications when it's mutated anyways).

You'll get notified if it's reassigned for some reason, but NSOperationQueue would have to take the trouble to make the notifications manually, or use the KVC accessors, to allow others to see when objects are added to or removed from its operations.

Comments