• GCD 开启一个定时器实现倒计时功能


     1     UIAlertView * alt = [[UIAlertView alloc] initWithTitle:@"提示"
     2                                                    message:@"操作成功,马上返回继续体验吧"
     3                                                   delegate:self
     4                                          cancelButtonTitle:@"留在当前"
     5                                          otherButtonTitles:@"马上返回", nil];
     6     [alt show];
     7     //倒计时时间
     8     __block int timeout = 5;
     9     dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
    10     dispatch_source_t source_t= dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0,queue);
    11     //每秒执行
    12     dispatch_source_set_timer(source_t,dispatch_walltime(NULL, 0),1.0*NSEC_PER_SEC, 0);
    13     dispatch_source_set_event_handler(source_t, ^
    14     {
    15         if(timeout<=0)
    16         {
    17             //倒计时结束,关闭
    18             NSString *strTime = [NSString stringWithFormat:@"倒计时,%.2ds后返回", 0];
    19             dispatch_async(dispatch_get_main_queue(), ^
    20             {
    21                 //设置界面的按钮显示 根据自己需求设置
    22                 alt.message = strTime;
    23                 [alt dismissWithClickedButtonIndex:1 animated:YES]; // 模拟的没有调用delegate方法
    24                 dispatch_source_cancel(source_t);
    25             });
    26         }
    27         else
    28         {
    29             // int minutes = timeout / 60;   //
    30             int seconds = timeout % 60; //
    31             NSString *strTime = [NSString stringWithFormat:@"倒计时,%.2ds后返回", seconds];
    32             dispatch_async(dispatch_get_main_queue(), ^
    33             {
    34                 //设置界面的按钮显示 根据自己需求设置
    35                 alt.message = strTime;
    36             });
    37             timeout--;
    38         }
    39     });
    40     dispatch_resume(source_t);
    View Code

    最后,奉上一篇博文 http://blog.csdn.net/chumeng411/article/details/20918895 这一篇博文中简单论述了timer与线程的关系可以参考一下。

  • 相关阅读:
    YII框架学习(二)
    YII框架学习(一)
    valid number 判断字符串是否为有效数字
    leetcode Add Binary
    leetcode Minimum Path Sum
    leetcode Unique Paths II
    leetcode[61] Unique Paths
    leetcode[60] Rotate List
    leetcode Permutation Sequence
    leetcode Spiral Matrix II
  • 原文地址:https://www.cnblogs.com/fuunnyy/p/5345062.html
Copyright © 2020-2023  润新知