Threaded Programming

Cocoa uses the NSThread class to provide multiple threads of execution in applications. Threads are useful if you want to perform a computationally intensive or time-consuming procedure in the background while allowing the main thread of execution to continue normally. When executing code in the main thread of the application, the flow of execution must stop while that code completes execution. If code takes a long time to execute, the user will notice that the application user interface controls freeze and do not respond to any actions.

To correct this problem, you could isolate the time-consuming code into its own method, and then execute that method in its own thread. This is how NSThread works—using the detachNewThreadSelector:toTarget:withObject: method, as shown in Example 2-38.

Example 2-38. Multithreading an application
                  // This method is invoked in response to some user action
- (void)someActionMethod:(id)sender
{
    [NSThread detachNewThreadSelector:@selector(longCode)
                             toTarget:self withObject:nil];
}

- (void)longCode
{
    NSAutoreleasePool *pool;
    pool = [[NSAutoreleasePool alloc] init];
    BOOL keepGoing = YES;

    while ( keepGoing) {
        // Do something here that will eventually stop by
                   // setting keepGoing to NO
    }

    [pool release];
}

As illustrated in Example 2-38, threads exit after the natural completion of a method. If the threaded method is to integrate properly with Cocoa objects, then that method is responsible for setting up and destroying its own autorelease ...

Get Cocoa in a Nutshell now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.