O'Reilly logo

Cocoa® by Richard Wentk

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

mac_ch11.eps
co_bar.eps

Chapter 11: Using Timers, Threads, and Blocks

mac_chbox11.eps

In This Chapter

Using NSTimer

Working with NSThread

Using NSOperation

Working with blocks and Grand Central Dispatch

Using NSTask

It's often useful to do many things at the same time. Cocoa offers a selection of classes and techniques for creating multiple simultaneous events and processes and for managing the relative and absolute timing of events. The newest classes use a new code idiom called blocks, which was introduced in OS X 10.6. Blocks can be used anywhere in an application, but Cocoa's event and data collection classes are being modified to support blocks where previously they used delegates and calls to other classes.

Using NSTimer

NSTimer is the simplest Cocoa event timing class. To trigger events at regular intervals, use:

NSTimer *theTimer = [NSTimer scheduledTimerWithTimeInterval: float

target: anObject

selector: @selector(theTimerMethod:)

userInfo: anOptionalObject

repeats: YES];

Implement the timer method in the target object:

-(void) theTimerMethod: (NSTimer *) theTimer {

//This code is called on every timer tick

}

To stop the timer, use

[myTimer invalidate];

The shortest possible interval is 0.0001s, but on ...

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