Several methods of delayed execution (sleep) of iOS

Source: Internet
Author: User

1. The most straightforward approach:

[self performselector:@selector (deleymethod) withobject: nil afterdelay:1. 0];

This method requires that it must be executed in the main thread, otherwise it is not valid. is a non-blocking method of execution that has not yet been found to cancel execution.

Cons: Write a method for the delay every time.

2. Use Nstread

[Nsthread Sleepfortimeinterval:0. 06];

This method can be executed in both the main thread and the child thread. is a blocking method of execution, which is placed in a sub-thread, so as not to get stuck in the interface, no way to cancel execution.

3.用GCD。

  Double delayinseconds = 2. 0;

dispatch_time_t poptime = Dispatch_time (Dispatch_time_now, delayinseconds * nsec_per_sec);

Dispatch_after (Poptime, Dispatch_get_main_queue (), ^ (void) {

//code to being executed on the main queue after delay

});

In this way, the executing thread can be selected in the parameter. is a non-blocking execution method that does not find a way to cancel execution.

4. Timer: Nstimer

[Nstimer scheduledtimerwithtimeinterval:1. 0f target:self selector:@selector (  Delaymethod) userInfo: nil repeats:NO];

This method requires that it must be executed in the main thread, otherwise it is not valid. is a non-blocking execution method that can be invalidate by the Nstimer class-(void);

5. Using Nsoperationqueue, execute in the next main loop of the application:

<span style="Background-color:rgb (255, 255, 255); ><span style="color: #000000;" >[[nsoperationqueue Mainqueue] addoperationwithblock:ablock];</span></span>

This and call Performselector:with Afterdelay of 0.0f equivalent

6. May not be a good way to use the completion parameter of animation

[UIView animatewithduration:0. 0 Delay:5. 0 Options: Uiviewanimationoptionallowuserinteraction animations:^{

} completion:^ (BOOL finished) {

//do stuff here

}];

Several methods of delayed execution (sleep) of iOS

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.