Sleep, Pause or Block a Thread

February 8, 2010admin No Comments »

If you ever need to briefly pause a thread of execution, there are two class methods in NSThread you can use. Although you have to use these methods judiciously, they can be handy in instances where you need to force a delay in order to achieve some desired effect.

For example, if you want to slowly fade-in (increase) the volume of the audio player over a few seconds, you could write a loop to bump the volume a small increment each time through the loop, and pause briefly before heading back to the top of the loop. If you didn’t include a short pause within the loop, the application may run the loop so quickly that you could not audibly detect the fade-in.

sleepForTimeInterval

One approach is to use the class method sleepForTimeInterval method:

+ (void)sleepForTimeInterval:(NSTimeInterval)ti

The variable NSTimeInterval is of type double and represents the number of seconds to sleep

// Block for .5 seconds
[NSThread sleepForTimeInterval:.5];
sleepUntilDate

Another approach is to use an NSDate object to specify a specific time in the future to resume the thread:

+ (void)sleepUntilDate:(NSDate *)aDate

With this method you pass in an NSDate object that specifies how long to block the thread.

// Block for 2.5 seconds from "now"
 NSThread sleepUntilDate: [NSDate dateWithTimeIntervalSinceNow:0.5]];

No related posts.

Join the discussion


My Zimbio
Top Stories