This paper lists four methods of delaying execution of a function and some differences. If the delay is 1 seconds, execute the following method.
-(void) Delaymethod {NSLog (@ "execute");}
1.performSelector method
[Self performselector: @selector (Delaymethod) withobject:nil afterdelay:1.0f];
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. 2. 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); 3. Sleep mode
[Nsthread sleepfortimeinterval:1.0f]; [Self delaymethod];
This method can be executed in both the main thread and the child thread. is a blocking execution, build justice placed in a sub-thread, so that the stuck interface does not find a way to cancel execution. 4.GCD mode
Double 1.0 ; __block Viewcontroller* bself = self ; = Dispatch_time (Dispatch_time_now, (int64_t) (delayinseconds *^ (void) { [bself Delaymethod]; });
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.
1. Delay method One (using methods in the Nsrunloop class to implement deferred execution, commonly used, performselector must be executed in the main thread) [self delayone]; 2. The delay method is two (commonly used in GCD mode) (This way you can select the thread to execute in the parameter.) is a non-blocking method of execution) __block Viewcontroller* Bself =Self ; Dispatch_after (Dispatch_time (Dispatch_time_now, (int64_t) (5.0* nsec_per_sec)), Dispatch_get_main_queue (), ^{[Bself isOneway]; }); 3. Delay method Three (must be performed in the main thread) Nstimer*timer = [Nstimer scheduledtimerwithtimeinterval:5.0ftarget:self selector: @selector (IsOneway) Userinfo:nil Repeats:no]; Cancellation method [Timer invalidate]; 4. Delay method Four (this mode can be executed in both the main thread and the child thread, is a kind of blocking execution, it is recommended to put in the sub-thread, so as not to get stuck in the interface) [Nsthread sleepfortimeinterval:5.0]; [Self isOneway];-(void) delayone{[self performselector: @selector (isOneway) withobject:nil Afterdelay:5.0f];}-(void) isoneway{Self.view.backgroundColor=[Uicolor Cyancolor];}View Code
Four ways to delay operations in IOS