O'Reilly logo

Cocoa in a Nutshell by James Duncan Davidson, Michael Beam

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

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 ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required