iOS: How to use a delay call to a method or execute a time or with intervals
In iOS or and its underlying Framework extends it to use Grand Central Dispatch (GCD).
So in this example, let say you wanted to call or execute a method at a specified time, you can use the code below,
Say you wanted to play an audio file after 2 seconds.
You need to call dispatch_get_main_queue() in order to add it and flag to the queue that this needs to be executed in the central main queue of the application.
This can be used for concurrency programming but take not of your variables also. You might also consider important keywords on handling your variables here such as making it atomic (i.e. w/o nonatomic in your property which by default, is atomic) when dealing with threads for thread-safety.
Another example also can be derive from Apple Developer's website,
Also, you might want to consider CADisplayLink class reference for handling timers with intervals. See http://stackoverflow.com/questions/5748700/iphone-a-question-about-dispatch-timers-and-timing
So in this example, let say you wanted to call or execute a method at a specified time, you can use the code below,
Say you wanted to play an audio file after 2 seconds.
- NSURL *audioURL = [[NSBundle mainBundle] URLForResource:@"TheAudioFile" withExtension:@"mp3"];
- NSError *error;
- AVAudioPlayer *audioPlayer = [[AVAudioPlayer alloc] initWithContentsOfURL:audioURL error:&error];
- dispatch_time_t popTime = dispatch_time(DISPATCH_TIME_NOW, 2.0 *NSEC_PER_SEC); // where 2.0 as a second * nano seconds
- dispatch_after(popTime, dispatch_get_main_queue(), ^(void) {
- [audioPlayer play];
- });
You need to call dispatch_get_main_queue() in order to add it and flag to the queue that this needs to be executed in the central main queue of the application.
This can be used for concurrency programming but take not of your variables also. You might also consider important keywords on handling your variables here such as making it atomic (i.e. w/o nonatomic in your property which by default, is atomic) when dealing with threads for thread-safety.
Another example also can be derive from Apple Developer's website,
dispatch_source_t CreateDispatchTimer(uint64_t interval, |
uint64_t leeway, |
dispatch_queue_t queue, |
dispatch_block_t block) |
{ |
dispatch_source_t timer = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, |
0, 0, queue); |
if (timer) |
{ |
dispatch_source_set_timer(timer, dispatch_walltime(NULL, 0), interval, leeway); |
dispatch_source_set_event_handler(timer, block); |
dispatch_resume(timer); |
} |
return timer; |
} |
void MyCreateTimer() |
{ |
dispatch_source_t aTimer = CreateDispatchTimer(30ull * NSEC_PER_SEC, |
1ull * NSEC_PER_SEC, |
dispatch_get_main_queue(), |
^{ MyPeriodicTask(); }); |
// Store it somewhere for later use. |
if (aTimer) |
{ |
MyStoreTimer(aTimer); |
} |
} |
Comments
Post a Comment