您的位置:首页 > 移动开发 > IOS开发

做一个100秒的倒计时程序,注意考虑程序进入后台时的情况

2013-07-20 21:25 344 查看
在.h文件中定义:

NSTimer * timer;//计时器

@property (nonatomic,retain) NSTimer *timer;

在.m文件中:

@synthesize timer;

int seconds = 100;//100秒

在didFinishLaunchingWithOptions方法中:

timer = [NSTimer scheduledTimerWithTimeInterval:1

                                                       target:self

                                                     selector:@selector(timerFireMethod:)

                                                     userInfo:nil

                                                      repeats:YES];//初始化计时器,每个1秒将会调用timerFireMethod方法

-(void)timerFireMethod:(NSTimer *)theTimer{

    if(seconds == 1){//当seconds还剩1s的适合停止计时器

        [theTimer invalidate];

    }else{

        seconds --;//实现倒计时功能

        NSLog(@"还剩%i秒",seconds);

    }

}

在applicationDidEnterBackground中//当应用进入后台时,停止计时

[timer setFireDate:[NSDate distantFuture]];

在applicationWillEnterForeground中//当应用进入前台时,继续计时

[timer setFireDate:[NSDate date]];

ps:由于本人这周才开始正式接触ios,所以有很多地方可能会出现一些bug,欢迎大家指出,相互交流,共同进步
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  ios
相关文章推荐