iOS - How to know when NSOperationQueue finish processing a few operations?

11,153

Solution 1

Add a "Done" NSOperation which has all other NSOperations for one directory as dependency.

Something like this:

NSInvocationOperation *doneOp = [[NSInvocationOperation alloc] initWithTarget:self selector:@selector(done:) object:nil];

NSInvocationOperation *op1 = [[NSInvocationOperation alloc] initWithTarget:self selector:@selector(doSomething:) object:nil];
[queue addOperation:op1];
[doneOp addDependency:op1];

NSInvocationOperation *op2 = [[NSInvocationOperation alloc] initWithTarget:self selector:@selector(doSomething:) object:nil];
[queue addOperation:op2];
[doneOp addDependency:op2];

NSInvocationOperation *op3 = [[NSInvocationOperation alloc] initWithTarget:self selector:@selector(doSomething:) object:nil];
[queue addOperation:op3];
[doneOp addDependency:op3];

[queue addOperation:doneOp];

doneOp will only run after op1, op2 and op3 have finished executing.

Solution 2

[opQueue operationCount]

Hope this helps

Share:
11,153
Dabrut
Author by

Dabrut

Updated on June 05, 2022

Comments

  • Dabrut
    Dabrut almost 2 years

    I need in my application to download directories and their content. So I decided to implement a NSOperationQueue and I subclassed NSOperation to implement NSURLRequest etc...

    The problem is I add all the operations at once and I can't figure out when all the files for one directory are downloaded in order to update the UI and enable this specific directory.

    Now I have to wait that all the files from all the directories are downloaded in order to update the UI.

    I already implemented key-value observing for the operationCount of the NSOperationQueue and the isFinished of the NSOperation but I don't know when a directory has all the files in it !

    Do you have any idea ?

    Thanks a lot

  • Dabrut
    Dabrut about 12 years
    That was my first idea. But I was wondering if that was the correct way to do it or if there was a better way to do it.
  • Dabrut
    Dabrut about 12 years
    I forgot to mention that my operations are concurrent. Is your example still ok ?
  • Matthias Bauch
    Matthias Bauch about 12 years
    Of course, that's the whole point of dependencies. In a non-concurrent operation queue you would just add your operations in the correct order to achieve the same. But an operation will not run until all its dependencies have finished executing.
  • Dabrut
    Dabrut about 12 years
    Kudos to you. That's exactly what I was looking for !
  • Phineas Lue
    Phineas Lue almost 9 years
    It is better than KVO approach because it is safer and more straightforward.
  • shim
    shim almost 9 years
    Does it matter whether you add the dependency before/after adding the operation to the queue?