IOS delayed execution (OC)

Source: Internet
Author: User

IOS delayed execution (OC)

This article lists four methods for delaying the execution of a function and their differences. If the latency is 1 second, execute the following method.

- (void)delayMethod{    NSLog(@"execute");}

1. performSelector Method
[self performSelector:@selector(delayMethod) withObject:nil afterDelay:1.0f];
This method must be executed in the main thread; otherwise, it is invalid.
Is a non-blocking execution method,
Currently, the method for canceling execution is not found.

 

2. Timer: NSTimer

[NSTimer scheduledTimerWithTimeInterval:1.0f target:self selector:@selector(delayMethod) userInfo:nil repeats:NO];
This method must be executed in the main thread; otherwise, it is invalid.
Is a non-blocking execution method.
You can cancel the execution through-(void) invalidate; of the NSTimer class.

3. sleep mode
[NSThread sleepForTimeInterval:1.0f]; [self delayMethod];
This method can be executed in both the main thread and sub-thread.
It is a blocking execution method. The Builder puts it in the Child thread to avoid getting stuck on the interface.
The method for canceling execution is not found.

4. GCD Mode
double delayInSeconds = 1.0; __weak __typeof(self)weakSelf = self;  dispatch_time_t popTime = dispatch_time(DISPATCH_TIME_NOW, (int64_t)(delayInSeconds * NSEC_PER_SEC));dispatch_after(popTime, dispatch_get_main_queue(), ^(void){     [weakSelf delayMethod]; });
In this way, you can select the thread to execute in the parameter.
Is a non-blocking execution method,
The method for canceling execution is not found.

 

 

Related Article

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.