NSTimer 实现简易倒计时

//定时器

m_pTimer = [NSTimer scheduledTimerWithTimeInterval:1.0

                                        target:self 

                                        selector:@selector(calcuRemainTime)

                                        userInfo:nil 

                                        repeats:YES];

//开始时间获取

m_pStartDate = [NSDate date];

//    m_pStartDate = [[NSDate date] retain];

 

 

==============

#define TOTAL_TIME 3600

/*

 *倒计时剩余时间计算

 */

- (void)calcuRemainTime

{

double deltaTime = [[NSDate date] timeIntervalSinceDate:m_pStartDate];

 

//    NSLog(@"%.f",deltaTime);

//    NSLog(@"%d",(int)(deltaTime+0.5));

 

int remainTime = TOTAL_TIME - (int)(deltaTime+0.5) ;

 

if (remainTime < 0.0

{

[m_pTimer invalidate];

//TODO:

//game over

return;

}

[self showTime:remainTime];

}

 

/*

 *在视图中显示时间

 */

- (void)showTime:(int)time

{

int inputSeconds = (int)time;

int hours =  inputSeconds / 3600;

int minutes = ( inputSeconds - hours * 3600 ) / 60

int seconds = inputSeconds - hours * 3600 - minutes * 60

NSString *strTime = [NSString stringWithFormat:@"%.2d:%.2d:%.2d",hours,minutes, seconds];

//显示在文本视图中

NSLog(@"==%@",strTime);

}


你可能感兴趣的:(ios,iPhone,倒计时,NSTimer)