views:

51

answers:

1

What is the best way to run code on a separate thread? Is it:

[NSThread detachNewThreadSelector: @selector(doStuff) toTarget:self withObject:NULL];

Or:

    NSOperationQueue *queue = [NSOperationQueue new];
NSInvocationOperation *operation = [[NSInvocationOperation alloc] initWithTarget:self
                                                                        selector:@selector(doStuff:)
                                                                          object:nil;
[queue addOperation:operation];
[operation release];
[queue release];

I've been doing the second way but the Wesley Cookbook I've been reading uses the first.

+3  A: 

In my opinion, the best way is with libdispatch, aka Grand Central Dispatch (GCD). It limits you to iOS 4 and greater, but it's just so simple and easy to use. The code to do some processing on a background thread and then do something with the results in the main run loop is incredibly easy and compact:

dispatch_async( dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
    // Add code here to do background processing
    //
    //
    dispatch_async( dispatch_get_main_queue(), ^{
        // Add code here to update the UI/send notifications based on the
        // results of the background processing
    });
});

If you haven't done so already, check out the videos from WWDC 2010 on libdispatch/GCD/blocks.

Jacques
I need it to be 3.0 compatible :(
Mike Simmons
Then operation queues are probably the next-best solution. Also, make sure you aren't diving into concurrency too quickly. Try starting by writing things single-threaded and profile to see if you need to go multithreaded, or if you can design your single-threaded code to be more efficient on its own. For simple tasks, you can sometimes do everything you need with performSelector:withObject:afterDelay: and avoid all of the issues that come with multi-threaded programming.
Jacques