Delayed calling of methods is often used in project development. The specific calling scenarios will not be described in detail. Several existing implementations are listed below. Method:
Method 1: performSelector Non-blocking execution mode will not affect other processes; must be executed in the main thread;
You can actively cancel the operation:[self performSelector:@selector(delayMethods) withObject:nil afterDelay:1.0];
If you want to cancel all current Delay operation:
[NSObject cancelPreviousPerformRequestsWithTarget:self selector:@selector(delayMethods) object:nil];
Note: This method is not safe enough. This method will set the timer in the current runloop when called. But we know that only the main thread will automatically run a runloop and contain a timer by default when it is created. Ordinary child threads do not have runloops and timers. So when called in a sub-thread, the delay operation code in our code will always wait for the timer to be scheduled, but in fact there is no timer in the sub-thread, which will cause our delay The action code is never executed.
Method 2: NSTimer[NSObject cancelPreviousPerformRequestsWithTarget:self];
Analysis: This method is a non-blocking execution method that will not affect other processes; it must be in the main Executed in the thread; the default is to set a timer in the main thread; you can set whether to repeat the delay operation;
Cancel the delay operation:
NSTimer *timer = [NSTimer scheduledTimerWithTimeInterval:1.0 target:self selector:@selector(delayMethods) userInfo:nil repeats:NO];
Note: If the repeats parameter is set to NO, the timer will be automatically destroyed after the execution is completed. If the repeats parameter is set to YES, after the execution is completed, [timer invalidate] must be manually called to destroy the timer;
Method three: sleep
[timer invalidate];
Analysis: This method is a blocking execution method. It is best to execute it in a child thread, otherwise it will affect the execution of other methods. .
Method 4: GCD
[NSThread sleepForTimeInterval:1.0];
Analysis: This method is a non-blocking execution method that will not affect other processes; it can be specified in the parameters Set the execution process in:
dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{ [self delayMethods]; });
You can also set whether to execute repeatedly:
dispatch_queue_t queen = dispatch_get_global_queue(0, 0); dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1.0 * NSEC_PER_SEC)), queen, ^{ [self delayMethods]; });
Note: Because this method is automatically processed by GCD , so it is not easy to cancel the operation
The above is the detailed content of Several delayed execution methods for iOS. For more information, please follow other related articles on the PHP Chinese website!