NSTimer详解

创建Timer的方法:

//创建并返回使用指定的调用对象初始化的新NSTimer对象

1、+ (NSTimer *)timerWithTimeInterval:(NSTimeInterval)ti invocation:(NSInvocation *)invocation repeats:(BOOL)yesOrNo;

//创建并返回使用指定对象和执行方法初始化的新NSTimer对象

2、+ (NSTimer *)timerWithTimeInterval:(NSTimeInterval)ti target:(id)aTarget selector:(SEL)aSelector userInfo:(nullable id)userInfo repeats:(BOOL)yesOrNo;

上面两个方法。创建了Timer但是并没有加入当前的运行循环。需要手动添加:

        //创建Timer

       _timer=[NSTimer timerWithTimeInterval:2 target:self selector:@selector(changeTimeValue) userInfo:nil repeats:YES];
       //必须手动加入到当前循环中去
       NSRunLoop *runloop=[NSRunLoop currentRunLoop];
       [runloop addTimer:_timer forMode:NSDefaultRunLoopMode];

      注释:     

       timerWithTimeInterval  //是设置一个时间间隔  上述代码是2秒后调用实例方法changeTimeValue

      target  //表示发送的对象 如:self

       @selector  //在一个时间间隔内选一个方法执行

      userInfo //此参数可以为nil   接收者的userInfo对象,在定时器失效后不要访问,可通过isValid判断是否有效

       repeats  //值为Yes或NO  Yse重复调用定时器方法,知道失效或释放。NO 只执行一次就失效

//创建并返回一个新的NSTimer对象,并在默认模式下在当前运行循环上调度它。

3、+ (NSTimer *)scheduledTimerWithTimeInterval:(NSTimeInterval)ti invocation:(NSInvocation *)invocation repeats:(BOOL)yesOrNo;

//创建并返回一个新的NSTimer对象,并在默认模式下在当前运行循环上调度它。
4、+ (NSTimer *)scheduledTimerWithTimeInterval:(NSTimeInterval)ti target:(id)aTarget selector:(SEL)aSelector userInfo:(nullable id)userInfo repeats:(BOOL)yesOrNo;

使用方法

            self.countDownTimer = [NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(timeCountDown) userInfo:nil repeats:YES];

上面两个方法创建的同时,加入了当前的运行循环中


//触发定时器的方法  fire 

当使用1,2方法手动添加runloop的定时器时可以调用fire方法立即触发

- (IBAction)startTimer:(id)sender {
    [_timer fire];
}

例如一个timer每次触发的时间是10秒,此时执行一次timer  的fire方法,本次Timer的触发时间就会变成9秒

//判断定时器是否失效

if([_timer isValid]){

    //有效

}

//移除定时器的方法 invalidate

使用方法:

 [_timer invalidate];





评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值