iOS开发:用NSTimer实现倒计时

首先定义NSTimer

NSTimer *timer = [NSTimer scheduledTimerWithTimeInterval:1.0 target:self selector:@selector(timerFireMethod:) userInfo:nil repeats:YES];

倒计时在timer的触发方法里完成

- (void)timerFireMethod:(NSTimer *)timer

{

    NSCalendar *calendar = [NSCalendar currentCalendar];

    NSDateComponents *components = [[NSDateComponents alloc] init];

    [components setYear:2012];

    [components setMonth:8];

    [components setDay:13];

    [components setHour:12];

    [components setMinute:0];

    [components setSecond:0];

    NSDate *fireDate = [calendar dateFromComponents:components];//目标时间

    NSDate *today = [NSDate date];//当前时间

    unsigned int unitFlags = NSYearCalendarUnit | NSMonthCalendarUnit | NSDayCalendarUnit | NSHourCalendarUnit | NSMinuteCalendarUnit | NSSecondCalendarUnit;

     NSDateComponents *d = [calendar components:unitFlags fromDate:today toDate:fireDate options:0];//计算时间差

    auctionTime.text = [NSString stringWithFormat:@"%d天%d小时%d%分%d秒", [d day], [d hour], [d minute], [d second]];//倒计时显示

}

这样就完成了倒计时。

不过如果有专门的服务器时,要把服务器和自己本机的时间差考虑进去

相关推荐