Adding Multi-Threaded Support Simply

January 21st, 2011 1 min read

When using operation queues in iOS, there are two ways to define the work you want to run on a background thread: subclass NSOperation or use the more specialised NSInvocationOperation. NSInvocationOperation (which is 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
                                                                        selector:@selector(foo)
                                                                          object:nil];

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:

_queue = [NSOperationQueue new]; // _queue is an instance variable, released in dealloc
[_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 background 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 Mastodon or Bluesky.

Keep reading