jlpiedrahita
jlpiedrahita

Reputation: 497

NSOperation with dependency not being executed when added to NSOperationQueue

I'm trying to figure out why a NSOperation with a dependency is not being executed when added to NSOperationQueue (iOS5, ARC):

@implementation NSOperationTest {
    NSOperationQueue *_operationQueue;
}

- (id)init {
    self = [super init];
    if (self) {
        _operationQueue = [[NSOperationQueue alloc] init];
    }
    return self;
}

-(void) test
{
    NSBlockOperation *op1 = [NSBlockOperation blockOperationWithBlock:^{
        NSLog(@"op1 running");
    }];

    NSBlockOperation *op2 = [NSBlockOperation blockOperationWithBlock:^{
        NSLog(@"op2 running");
    }];

    [op2 addDependency:op1];
    [_operationQueue addOperation:op2];
}
@end

This is getting me crazy, here op1 is supposed to be executed before op2, but either is executed, when added without dependencies both works just fine. Does someone knows why?

Thanks in advance.

Upvotes: 1

Views: 1549

Answers (1)

Andrew R.
Andrew R.

Reputation: 943

You have to explicitly any operation to the operation queue (or execute it directly) in order for it to execute - and dependencies are no exception. Without doing so (as you've done) op2 will never execute because it is waiting for op1 to execute, when op1 has never been told to execute. So by adding [_operationQueue addOperation: op1]; at the end of your test method, your problem should be fixed.

Upvotes: 6

Related Questions