pausing execution for 1 second
I have an IBAction which starts a number of timers.
I would like to have a second or a pause for a certain time. How can I pause execution?
I know of the [self performSelector:@selector(someMEthod:) withObject:someObj开发者_运维知识库ect afterDelay:1.0];
but how can I just cause a delay without calling anything?
Thanks
You can call sleep()
or +[NSThread sleepForTimeInterval:]
but please don't do that on the main thread. Pausing execution of the main thread means your app's UI will be blocked for that time and appear to the user as if it had crashed. If you blocked the main thread for more than a few seconds, Apple's watchdog timer would kill your app instantly.
See this blog post by Jeff LaMarche for more on this issue: http://iphonedevelopment.blogspot.com/2010/05/psa-respect-main-thread.html
You don't want to cause a delay without calling anything. It's bad for the UI, and does not fit Cocoa Touch's event driven paradigm.
Cut the routine in which you want to pause into (at least) two parts/halves. Have the first half set up a delayed call to the second half (perform selector with delay, timer, queue, etc.) and then return to the main loop. The OS will call the second part, later, after potentially doing useful stuff in the mean time (giving the user a responsive UI or saving battery life, catching up with background email, etc.)
You may have to learn how to save state between parts (loop variables, etc.), something that some new programmers seem to miss in their learning.
You can use sleep(int_No_of_Sec); // eg. sleep(1);
精彩评论