Nikita P
Nikita P

Reputation: 4246

NSOperationQueue concurrent operations with new threads starting inside operations

I have just started using NSOperation/NSOprationQueue, so forgive me for asking this question. :P

At the start of my app, I want some set of functions to be performed in a queue, so that when one ends, another starts (I have set setMaxConcurrentOperationCount to 1 so that only one operation occurs at a time). All should happen in background, as its a kind of a download/upload to server of information.

I put the first operation in the queue, that calls another method, which may invoke some new threads to perform some other actions.

My question is, Will the Operation Queue wait for all the methods/threads started in the first operation to complete before starting second operation?

Upvotes: 3

Views: 538

Answers (3)

Sunil_Vaishnav
Sunil_Vaishnav

Reputation: 425

You can use something like this

NSOperationQueue *queue=[NSOperationQueue new];
[queue setMaxConcurrentOperationCount:1];
NSBlockOperation *blockOperation1 = [NSBlockOperation blockOperationWithBlock:^{
    //operation first
}];
NSBlockOperation *blockOperation2 = [NSBlockOperation blockOperationWithBlock:^{
    //operation second
}];
[blockOperation2 addDependency:blockOperation1];
[queue addOperation:blockOperation1];
[queue addOperation:blockOperation2];

Upvotes: 0

Atif Khan
Atif Khan

Reputation: 125

If NSOperation is doing asynchronous task like something like [NSURLConnection sendAsynchronousRequest:.....] than the thread on which operation is running wont wait for response, and it will not wait. As soon main method last statement or block last statement is executed operation would be remove from queue and next operation would start.

Upvotes: 0

zoul
zoul

Reputation: 104065

There are two kinds of NSOperations, concurrent and non-concurrent.

The non-concurrent operations are implemented in their -main method, and when this method returns, the operation is considered done. If you spawn a thread inside -main and want the operation to run until the thread is finished, you should block the execution in -main until the thread is done (using a semaphore, for example).

The concurrent operations have a set of predicates like -isExecuting and -isFinished, and there’s a -start method that starts the operation. This method may just spawn some background processing and return immediately, the whole operation is not considered finished until -isFinished says so.

Now that we have GCD it’s usually a good idea to consider blocks and dispatch queues as a lighter alternative to NSOperation, also see the –addOperationWithBlock: method on NSOperationQueue.

Upvotes: 1

Related Questions