Original: http://blog.csdn.net/kylinbl/article/details/8972261
Method 1: Use Nstimer to implement
The main use of the Nstimer Scheduledtimerwithtimeinterval method to perform a timefiremethod function every 1 seconds, timefiremethod the countdown of some operations, When finished, the timer is invalidate off, the code is as follows:
[CPP]View Plaincopyprint?
- Secondscountdown = 60; //60 Seconds Countdown
- Countdowntimer = [Nstimer scheduledtimerwithtimeinterval:1 target:self selector: @selector (timefiremethod) UserInfo: Nil Repeats:yes];
- -(void) timefiremethod{
- secondscountdown--;
- if (secondscountdown==0) {
- [Countdowntimer invalidate];
- }
- }
Method 2: Use GCD to implement
The code is as follows:
[CPP]View Plaincopyprint?
- __block int timeout=300; //Countdown time
- dispatch_queue_t queue = Dispatch_get_global_queue (Dispatch_queue_priority_default, 0);
- dispatch_source_t _timer = dispatch_source_create (dispatch_source_type_timer, 0, 0,queue);
- Dispatch_source_set_timer (_timer,dispatch_walltime (NULL, 0), 1.0*nsec_per_sec, 0); //per second execution
- Dispatch_source_set_event_handler (_timer, ^{
- if (timeout<=0) { //countdown end, close
- Dispatch_source_cancel (_timer);
- Dispatch_release (_timer);
- Dispatch_async (Dispatch_get_main_queue (), ^{
- Set the interface button to display the settings according to your needs
- 。。。。。。。。
- });
- }else{
- int minutes = TIMEOUT/60;
- int seconds = timeout% 60;
- NSString *strtime = [NSString stringwithformat:@"%d minutes%.2d seconds after re-obtaining the verification code", minutes, seconds];
- Dispatch_async (Dispatch_get_main_queue (), ^{
- //Set the interface button to display according to your own needs settings
- 。。。。。。。。
- });
- timeout--;
- }
- });
- Dispatch_resume (_timer);
Two ways to implement the countdown to "go" iOS development