Multithreading
These notes describe the basics of multithreading in Objective C.
Typical NSThread Use Case
- (void)someAction:(id)sender {
// Fire up a new thread
[NSThread detachNewThreadSelector:@selector(doWork:) toTarget:self withObject:someData];
}
- (void)doWork:(id)someData {
NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
[someData doLotsOfWork];
// Message back to the main thread
[self performSelectorOnMainThread:@selector(allDone:) withObject:[someData
result] waitUntilDone:NO];
[pool release];
}
NSOperations
An alternative to threads is a higher level construct called an operation that manages the thread creation and encapsulates the work in an object. You can create your own subclass or use the already defined NSInvocationOperation subclass with an NSOperationQueue.
- (void)someAction:(id)sender {
NSInvocationOperation *operation = [[NSInvocationOperation alloc]
initWithTarget:self
selector:@selector(doWork:)
object:someObject];
[queue
addOperation:operation];
[operation
release];
}
This creates the operation which will perform doWork in a separate thread.
The NSOperationQueue determines which threads run concurrently and their
priorities. When doWork is complete the method allDone is executed with
the parameter [someData result].