Chapter 11: Using Timers, Threads, and Blocks


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

Get Cocoa® now with the O’Reilly learning platform.

O’Reilly members experience live online training, plus books, videos, and digital content from nearly 200 publishers.