NSTimer详解

    xiaoxiao2021-03-26  25

    创建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];

    转载请注明原文地址: https://ju.6miu.com/read-661263.html

    最新回复(0)