How to make thread sleep for seconds in iOS?

后端 未结 5 1976
予麋鹿
予麋鹿 2021-02-04 19:39

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.

相关标签:
5条回答
  • 2021-02-04 19:50

    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];
    
    0 讨论(0)
  • 2021-02-04 20:00

    it cannot be easier.

    sleep(seconds);
    
    0 讨论(0)
  • 2021-02-04 20:00

    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 
    });
    
    0 讨论(0)
  • 2021-02-04 20:02

    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

    0 讨论(0)
  • 2021-02-04 20:11

    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.

    0 讨论(0)
提交回复
热议问题