IOS: several methods of delayed execution (sleep), ios latency
1. The most direct method:
[Self defined mselector: @ selector (deleyMethod) withObject: nil afterDelay: 1.0];
This method must be executed in the main thread; otherwise, it is invalid. Is a non-blocking execution method, and the method for canceling execution is not found at the moment.
Disadvantage: Write a method for the delay each time.
2. Use
NSTread
[NSThread sleepForTimeInterval: 0.06];
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 sub-thread to avoid getting stuck on the interface. The method for canceling the execution is not found.
3. Use 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 be executed on the main queue after delay
});
In this way, you can select the thread to execute in the parameter. Is a non-blocking execution method, and the method for canceling the execution is not found.
4. 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 use the NSTimer class-(void) invalidate; to cancel the execution.
5. Use NSOperationQueue to execute the following main loop in the application:
<Span style = "background-color: rgb (255,255,255);"> <span style = "color: #000000;"> [[NSOperationQueue mainQueue] addOperationWithBlock: aBlock]; </span>
This is equivalent to calling mongomselector: with afterDelay of 0.0f.
6. It may be a bad method. Use the completion parameter of animation.
[UIView animateWithDuration: 0.0 delay: 5.0 options: UIViewAnimationOptionAllowUserInteraction animations: ^ {
} Completion: ^ (BOOL finished ){
// Do stuff here
}];