How to make thread sleep for seconds in iOS?

后端 未结 5 2099
予麋鹿
予麋鹿 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条回答
  •  萌比男神i
    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

提交回复
热议问题