Adding multi-threaded support simply

January 21st, 2011

In iOS there are two ways to support multi-threading in your app: subclass NSOperation or use the more specialised NSInvocationOperation. NSInvocationOperation (which a concrete subclass of NSOperation) is intended to perform work using the target-action pattern. So whereas with a standard NSOperation subclass we would create a whole new class, with NSInvocationOperation we pass in a selector and when that NSInvocationOperation instance is executed it will call that method on a background-thread. For simple tasks, NSInvocationOperation offers a lightweight approach to push work onto a background-thread.

A photo of colourful thread

Adding multi-threading support

Let's create an NSInvocationOperation instance and have it call a method (foo) on self:

NSInvocationOperation *operation = [[NSInvocationOperation alloc] initWithTarget:self

foo is a simple method that prints out the description of the main-thread and the description of the thread foo is being executed on:

- (void)foo {
    NSLog(@"Main thread is: %@", [NSThread mainThread]);
    NSLog(@"`foo`, is executing on thread: %@", [NSThread currentThread]);

Now that we have our operation, we just need to add it to a queue:

NSOperationQueue *queue = [NSOperationQueue new];
[queue addOperation:operation];
[operation release];

After combining the above snippets, if you run the resulting solution, you should see that foo is being called on a background-thread 🕺.

Please note, that you should avoid accessing or updating the UI from a secondary thread. Instead, use: performSelectorOnMainThread:withObject:waitUntilDone: to push work back onto the main-thread.

What do you think? Let me know by getting in touch on Twitter - @wibosco