views:

592

answers:

5

I have a few method calls like this:

[self myFoo];
[self heavyStuff]; // this one in other thread
[self myBar];

which classes / methods do I have to look at? When I search for "thread", there comes a lot of classes, methods and functions. Which one's are most apropriate here?

+11  A: 

You would do

[self performSelectorInBackground:@selector(heavyStuff) withObject:nil];

See the NSObject reference on Apple's site.

Marc W
+4  A: 

You could use NSOperationQueue and NSInvocationOperation:

[self myFoo];

NSOperationQueue *operationQueue = [[NSOperationQueue alloc] init];
NSInvocationOperation *operation = [[NSInvocationOperation alloc] initWithTarget:self                   selector:@selector(heavyStuff) object:nil];
[operationQueue addOperation:operation];

[self myBar];
QAD
+11  A: 

For "fire and forget", try [self performSelectorInBackground:@selector(heavyStuff) withObject:nil]. If you have more than one operation like this, you may want to check out NSOperation and its subclass NSInvocationOperation. NSOperationQueue managed thread pooling, number of concurrently executing operations and includes notifications or blocking methods to tell you when all operations complete:

[self myFoo];

NSOperationQueue *operationQueue = [[NSOperationQueue alloc] init];
NSInvocationOperation *operation = [[NSInvocationOperation alloc] initWithTarget:self                                                                                                                                   selector:@selector(heavyStuff) object:nil];

[operationQueue addOperation:operation];
[operation release];

[self myBar];

...

[operationQueue waitUntilAllOperationsAreFinished]; //if you need to block until operations are finished

At a lower level, you can use use -[NSThread detachNewThreadSelector:@selector(heavyStuff) toTarget:self withObject:nil].

Barry Wark
missing a 'g' in performSelectorInBackround
Erich
fixed. thanks @Erich.
Barry Wark
+7  A: 

You've got lots of great pointers here, but don't forget to spend some time with the Threading Programming Guide. It provides good guidance not only on the technologies, but also good design of concurrent processing, and how to make better use of the run loop both with threads and instead of threads.

Rob Napier
+2  A: 

If you're targeting Snow Leopard exclusively, you can use Grand Central Dispatch:

 [self myFoo];
 dispatch_async(dispatch_get_global_queue(0, 0), ^{
     [self heavyStuff];
     dispatch_async(dispatch_get_main_queue(), ^{
       [self myBar];
     });
 });

But it won't run on earlier systems (or the iPhone) and is probably overkill.

Frank Schmitt
NSOperation also uses GCD in Snow Leopard, and it includes an NSBlockOperation subclass so you can use blocks with it.
Chuck