There are four ways to initialize 1,nstimer, which are divided into timerwithtimeinterval and scheduledtimerwithtimeinterval .
1 + (Nstimer *) Timerwithtimeinterval: (nstimeinterval) ti invocation: (nsinvocation *) invocation repeats: ( BOOL) Yesorno; 2 + (Nstimer *) Scheduledtimerwithtimeinterval: (nstimeinterval) ti invocation: (nsinvocation *) invocation Repeats: (BOOL) Yesorno; 3 4 + (Nstimer *) Timerwithtimeinterval: (nstimeinterval) TI target: (ID) atarget selector: (SEL) Aselector UserInfo: (ID) UserInfo repeats: (BOOL) Yesorno; 5 + (Nstimer *) Scheduledtimerwithtimeinterval: (nstimeinterval) TI target: (ID) atarget selector: (SEL) Aselector UserInfo: (ID) UserInfo repeats: (BOOL) Yesorno;
2, initialization method with different points beginning with Timerwithtimeinterval and Scheduledtimerwithtimeinterval
Code Description:
First case
1Timer1 = [Nstimer timerwithtimeinterval:1Target:self selector: @selector (time) Userinfo:nil Repeats:yes];//initialization starting with Timerwithtimeinterval2[[Nsrunloop Currentrunloop] Addtimer:timer1 Formode:nsdefaultrunloopmode];//Manual Addtimer:formode required: Adding a timer to a runloop3[Timer1 fire];//need to call the system's own-(void) fire; method to trigger the timer immediately4 5- (void) Time6 {7 if(Alltime >1){8Alltime--;9_codelabel.text = [NSString stringWithFormat:@"%ds", alltime];Ten}Else{ One[Timer setfiredate:[nsdate distantfuture];//Turn off the timer A } -}
The second case
Timer = [Nstimer scheduledtimerwithtimeinterval:1Target:self selector: @selector (Timedown) Userinfo:nil Repeats:yes];//initialization of the scheduled start//automatic triggering, executed every 1 seconds, because the scheduled initialization method will be added directly to the current runloop with the default mode- (void) timedown{if(Alltime >1) {alltime--; _codelabel.text= [NSString stringWithFormat:@"%ds", Alltime]; }Else{[timer setfiredate:[nsdate distantfuture]];//Turn off the timer }}
The first case is the same as the second, but the first case needs to be manually added to the runloop , then the fire is manual, and the second is a little simpler than it looks. So usually we can use the second type, the code is concise;
Other knowledge points of 3,nstimer
// This is the only way to move the timer out of the Runloop. -(void) invalidate;
Turn off the timer, when the condition is reached, do not need to use the timer to shut down, prevent the class to leak, otherwise the timer will continue to execute
[Timer setfiredate:[nsdate distantfuture];
turn on the timer, you can call this method when you need to start the timer again, but only if the timer is not removed
[Timer setfiredate:[nsdate Distantpast];
Use of Timer Nstimer in iOS