2
votes

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
        }
    }
}
2

2 Answers

2
votes

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.

1
votes

I had a similar need and created a very thin operations manager, OperationsRunner in this github project. Other objects interface with this class instead of the NSOperationsQueue directly. It has only a handful of methods - run an operation, cancel it, ask for the number of operations in the queue, etc.

What I did was to use a mutable set to hold a reference to an operation that was added to the operations queue, and remove it when the operation completed or cancelled - sort of a shadow container.

The nice this about this class is that you can easily add it to any kind of other class to manage operations, and quickly cancel all pending operations.