Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>I would suggest using a <code>NSOperationQueue</code> with a <code>NSInvocationOperation</code>. The <code>NSOperationQueue</code> will automatically scale to use as many threads as is optimal under current load, and is intended for executing long running tasks. There is nothing that stops you from calling back to your delegate several times from an operation running on a operation queue.</p> <p>Setup your queue like this:</p> <pre><code>NSOperationQueue* queue = [[NSOperationQueue alloc] init]; </code></pre> <p>I assume that you want no extra arguments sent to your task but the delegate to report back to. In this scenario using a plain <code>NSInvocationOperation</code> is easiest. I also assume that the method that implements the task, and the method that receives the callback are in the same class. Start a task like so:</p> <pre><code>NSInvocationOperation* operation; operation = [[NSInvocationOperation alloc] initWithTarget:self selector:@selector(executeTask:) object:self]; [queue addOperation:operation]; [operation release]; </code></pre> <p>And then implement <code>executeTask:</code>. Call back to the delegate on the main thread, so that the UI can safely be updated in the callback. You could wait for the callback to complete if you like, but I skip this, all callbacks will be queued on the main thread.</p> <pre><code>-(void)executeTask:(id)delegate; { while (notDone) { NSAutoreleasePool* pool = [[NSAutoreleasePool alloc] init]; [delegate performSelectorOnMainThread:@selector(taskWillProgress:) withObject:self waitUntilDone:NO]; // Do stuff [pool release]; }; } </code></pre> <p>I have also thrown in a local autorelease pool. This can be necessary when doing lengthy work in background tasks without a run-loop in place. Good practice.</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload