NSInvocationOperation - A simple mans threading

There are two ways to introduce threading into your applications, you could subclass or use the NSInvocationOperation object. Here we're going to use NSInvocationOperation.

Let's get started: what you need is a queue and some objects to wait in that queue.

The Queue

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

Here we are creating the data structure that will store all of our NSInvocationOperation objects. It gradually works its way through those objects in the queue and execute them. NSOperationQueue is set to autorelease so no need to do anything more there. In the next line I tell this queue to only execute one operation at a time.

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 queue

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

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

-(void)methodA{
      //Do some work

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

Here is an example of how methodA may look. I've omitted the thread specific code as its just normal Objective-C statements, however I've shown how we communicate with the main thread and pass any data back to it.

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