Two countdown implementation methods for ios development

Source: Internet
Author: User

Method 1: Use nstimer

It mainly uses the scheduledtimerwithtimeinterval method of nstimer to execute the timefiremethod function every second. timefiremethod performs some countdown operations. After timer is completed, it is OK to give invalidate. The Code is as follows:

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:

_ Block int timeout = 300; // countdown time dispatch_queue_t queue = minute (hour, 0); dispatch_source_t _ timer = dispatch_source_create (hour, 0, 0, queue ); dispatch_source_set_timer (_ timer, dispatch_walltime (NULL, 0), 1.0 * NSEC_PER_SEC, 0); // second (_ timer, ^ {if (timeout <= 0) {// The countdown ends. Disable dispatch_source_cancel (_ time R); dispatch_release (_ timer); dispatch_async (dispatch_get_main_queue (), ^ {// the buttons on the settings page are displayed as needed ........ });} Else {int minutes = timeout/60; int seconds = timeout % 60; NSString * strTime = [NSString stringWithFormat: @ "% d %. get the verification code ", minutes, seconds]; dispatch_async (dispatch_get_main_queue (), ^ {// you can set the settings according to your needs ........ }); Timeout -- ;}}); dispatch_resume (_ timer );



Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.