分享

NSTimer 使用 绝对超详细(1)

 最初九月雪 2014-12-04

先说一下我的业务需求,最近在做一个小项目,需要用到定时器的功能,NSTimer类,期间,出现了一些小问题,不过最终通过自己的努力,终于做出来了。我想总结一下,我对NSTimer类的学习和理解。

不多说了,先上效果图


界面元素很简单,两个UIButton 开始和暂停,20表示起始倒计时。最终的效果是,按开始按钮的时候,倒计时开始运行,按暂停按钮的时候,计时器,停止倒计时。当倒计时为0的时候,弹出一个对话框,提示时间已到。


业务需求很简单,但是,在我的实现中,却出现了,一些小错误。 主要是暂停键不能点击多次,开始键也不能点击多次,我相信,刚开始,接触这个NSTimer的人,也会出现这几个问题。


直接上几个主要的代码:

控制器类的.h文件中

@interface sdsViewController : UIViewController<UIAlertViewDelegate>

//定义一个定时器,做为实例变量
@property(nonatomic,retain) NSTimer *timer;

//显示倒计时当前状态
@property (retain, nonatomic) IBOutlet UILabel *timeDisplay;

//开始按钮,响应的action
- (IBAction)startTime:(id)sender;

//暂停按钮响应的action
- (IBAction)stopTime:(id)sender;

@end



.m中关键代码

开始按钮 响应代码

- (IBAction)startTime:(id)sender {


 //如果定时器对象不存在,则创建一个并启动
    
    if(!_timer){
        
        //创建一个定时器,这个是直接加到当前消息循环中,注意与其他初始化方法的区别
       _timer=[NSTimer scheduledTimerWithTimeInterval:1.0 target:self selector:@selector(changeTimeAtTimedisplay) userInfo:nil repeats:YES]; 


        //  [_timer fire]; //对于这个fire方法,稍后会详解,它不是启动一个定时器,这么简单
        
    }


}

//结束按钮响应代码:


- (IBAction)stopTime:(id)sender {
    
    if (_timer) {
        NSLog(@"调用 self.time为真!!");


            //如果定时器在运行
        if ([self.timer isValid]) {


            NSLog(@"单击停止按钮,取消定时器!!");
       
            [self.timer invalidate];

        //这行代码很关键
           _timer=nil;

            
        }
        
    }
    
}

一切OK,现在分析程序用到的关键地方。

先看看NSTimer类的结构,比较简单

Tasks

Creating a Timer

//创建一个定时器 ,以下是便利构造器方法,都懂的
+ scheduledTimerWithTimeInterval:invocation:repeats:
+ scheduledTimerWithTimeInterval:target:selector:userInfo:repeats:

+ timerWithTimeInterval:invocation:repeats:
+ timerWithTimeInterval:target:selector:userInfo:repeats:

//初始化方法
– initWithFireDate:interval:target:selector:userInfo:repeats:


//是开始一个定时器吗,恐怕没那么简单????????
Firing a Timer
– fire

//是暂停一个定时器吗,NO ,是Stop ,写的很清楚

Stopping a Timer
– invalidate

//关于定时器的以下信息
Information About a Timer
– isValid  //是否在运行
– fireDate //Returns the date at which the receiver will fire.
– setFireDate: //重新设置定时器开始运行的时间
– timeInterval  //定时器延时时间
– userInfo //其他信息



    本站是提供个人知识管理的网络存储空间,所有内容均由用户发布,不代表本站观点。请注意甄别内容中的联系方式、诱导购买等信息,谨防诈骗。如发现有害或侵权内容,请点击一键举报。
    转藏 分享 献花(0

    0条评论

    发表

    请遵守用户 评论公约

    类似文章 更多