Comparison and summarization of several delayed execution methods in iOS, ios latency
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. It is recommended that you put 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;__block ViewController* bself = self;dispatch_time_t popTime = dispatch_time(DISPATCH_TIME_NOW, (int64_t)(delayInSeconds * NSEC_PER_SEC));dispatch_after(popTime, dispatch_get_main_queue(), ^(void){ [bself delayMethod];});
In this way, you can select the thread to execute in the parameter.
Is a non-blocking execution method,
No Cancellation Method Found