zoukankan      html  css  js  c++  java
  • iOS-NSTimer

    一、倒计时的实现(老代码,只提供思路,最新的用法请参阅最新的sdk对应的文档)

    开始运行viewDidLoad的时候加载 [NSTimerscheduledTimerWithTimeInterval:1.0 target:selfselector:@selector(timerFireMethod:) userInfo:nilrepeats:YES];//使用timer定时,每秒触发一次
    ,然后就是写selector了。
     
    -(void)timerFireMethod:(NSTimer*)theTimer
    {
     //NSDateFormatter *dateformatter =[[[NSDateFormatter alloc]init]autorelease];//定义NSDateFormatter用来显示格式
     //[dateformatter setDateFormat:@"yyyy MM dd hh mmss"];//设定格式
     NSCalendar *cal = [NSCalendarcurrentCalendar];//定义一个NSCalendar对象
     NSDateComponents *shibo = [[NSDateComponentsalloc] init];//初始化目标时间(好像是世博会的日期)
     [shibo setYear:2010];
     [shibo setMonth:5];
     [shibo setDay:1];
     [shibo setHour:8];
     [shibo setMinute:0];
     [shibo setSecond:0];
     
     NSDate *todate = [caldateFromComponents:shibo];//把目标时间装载入date
     [shibo release];
    // NSString *ssss = [dateformatterstringFromDate:dd];
    // NSLog([NSString stringWithFormat:@"shiboshi:%@",ssss]);
     
     NSDate *today = [NSDate date];//得到当前时间
    // NSString *sss = [dateformatterstringFromDate:today];
    // NSLog([NSString stringWithFormat:@"xianzaishi:%@",sss]);
     //用来得到具体的时差
     unsigned int unitFlags = NSYearCalendarUnit |NSMonthCalendarUnit | NSDayCalendarUnit | NSHourCalendarUnit |NSMinuteCalendarUnit | NSSecondCalendarUnit;
     NSDateComponents *d = [cal components:unitFlagsfromDate:today toDate:todate options:0];
     lab.text = [NSStringstringWithFormat:@"%d年%d月%d日%d时%d分%d秒",[d year],[d month], [d day],[d hour], [d minute], [d second]];
    }
    这样就实现了倒计时的功能。

    二、timer的常用方法(亲试,截止到202008,这些代码依然是可用的)

    定义一个 weak修饰的 timeraa 

    @property (nonatomic, weak) NSTimer * timeraa;

    初始化

    self.timeraa = [NSTimer scheduledTimerWithTimeInterval:1.0f target:self selector:@selector(XXXX) userInfo:nil repeats:YES];

     暂停timer

    [self.timeraa setFireDate:[NSDate distantFuture]];

    继续timer

    [self.timeraa setFireDate:[NSDate distantPast]];

    页面dealloc之前释放掉timer

    [self.timeraa invalidate];

    self.timeraa = nil;

  • 相关阅读:
    94、二叉树的中序遍历 | JS
    102、二叉树的层序遍历 | JS
    111、二叉树的最小深度 | JS
    二叉树的先中后序遍历-JS非递归实现
    二叉树的先中后序遍历-JS递归实现
    深度和广度优先遍历-JS实现
    76、最小覆盖子串 | JS-字典
    extra1 二分查找与二叉判定树
    02 线性表的顺序存储
    原型、原型链、作用域、作用域链、闭包
  • 原文地址:https://www.cnblogs.com/isItOk/p/5228104.html
Copyright © 2011-2022 走看看