A simple threading approach

There are two ways to introduce threading into your applications, you could subclass NSOperation or use NSInvocationOperation. Here we're going to use NSInvocationOperation to build a simple multi-threaded app.

The Queue

NSOperationQueue *queue = [NSOperationQueue new];
[queue setMaxConcurrentOperationCount:1];

Here we are creating the data structure that will store all of our NSInvocationOperation objects. NSOperationQueue gradually works its way through those objects in its queue and executes them. NSOperationQueue is set to autorelease so no need to do anything more there. [queue setMaxConcurrentOperationCount:1] tells to queue to only execute one operation at a time.

Adding objects to queue

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

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

Here we are creating two operations. In quererA we are telling it that when it is its turn to execute it should call a methodA, which it will then execute as normal. quererB is the same.

Add objects to the queue

[queue addOperation:queuerA];
[queuerA release];
[queue addOperation:queuerB];
[queuerB release];

Here we are adding the operation objects to the queue in the order we want them to execute in.

    //Do some work

    //communicate with main thread to tell it we are finished doing work
    [self.view performSelectorOnMainThread:@selector(updateView) withObject:nil waitUntilDone:YES];

Above is an example of how methodA may look. I've omitted the non-thread specific code to highlight how we can communicate with the main thread from our background thread and pass any data back to it.

Please note, that you should avoid accessing or updating the UI from a secondary thread.

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