In iOS env, is it possible to make current thread sleep for seconds, then execute my code? NSTimer, GDC or any technique is okay for me.
Use the class 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];
it cannot be easier.
sleep(seconds);
Either
[self performSelector:@selector(YourFunctionName) withObject:(can be Self or Object from other Classes) afterDelay:(Time Of Delay)];`
or
dispatch_after(dispatch_time(DISPATCH_TIME_NOW, 1 * NSEC_PER_SEC),
dispatch_get_main_queue(), ^{
//your method
});
It would be better if you shared what you have done but it here you go.
There are a few options you can go with:
Option 1
// Standard Unix calls
sleep();
usleep();
Some documentation regarding the sleep
function can be found here. You'll find that they are actually C
functions but since Objective-C
is a strict superset of C we can still use the sleep
and usleep
functions.
Option 2
[NSThread sleepForTimeInterval:2.000];//2 seconds
The Apple documentation for this method states:
Sleeps the thread for a given time interval.
Discussion
No run loop processing occurs while the thread is blocked.
Option 3
dispatch_after(dispatch_time(DISPATCH_TIME_NOW,
1 * NSEC_PER_SEC),
dispatch_get_main_queue(),
^{
// Do whatever you want here.
});
The Grand Central Dispatch
route is a pretty good way of doing things as well. Here is the Apple Documentation for Grand Central Dispatch which is quite a good read.
There is also this question that might be pretty useful How to Wait in Objective-C
it depends how you are creating (spawning) your threads. For example if you are creating your thread with NSThread
class, you can use the two class methods :
sleepUntilDate:
sleepForTimeInterval:
But generally it's a bad idea to handle the threading management yourself, because multithreading programming is very hard. You can use GCD or operations queues for example to handle the multithreading in your application.