zoukankan      html  css  js  c++  java
  • NSTimer scheduledTimerWithTimeInterval与timerWithTimeInterval、initWithFireDate的区别

    英文原文是这样的:

    A timer object can be registered in only one run loop at a time, although it can be added to multiple run loop modes within that run loop. There are three ways to create a timer:

    Once scheduled on a run loop, the timer fires at the specified interval until it is invalidated. A non-repeating timer invalidates itself immediately after it fires. However, for a repeating timer, you must invalidate the timer object yourself by calling its invalidate method. Calling this method requests the removal of the timer from the current run loop; as a result, you should always call the invalidate method from the same thread on which the timer was installed. Invalidating the timer immediately disables it so that it no longer affects the run loop. The run loop then removes the timer (and the strong reference it had to the timer), either just before the invalidate method returns or at some later point. Once invalidated, timer objects cannot be reused.

     

    翻译过来大体是这样的:

    有三种方法来创建一个定时器

    1.使用scheduledTimerWithTimeInterval

    类方法创建计时器和进度上当前运行循环在默认模式(NSDefaultRunLoopMode)

    2.使用timerWithTimerInterval

    类方法创建计时器对象没有调度运行循环(RunLoop)

    在创建它,必须手动添加计时器运行循环,通过调用adddTimer:forMode:方法相应的NSRunLoop对象

    3.使用initWithFireDate

    在创建它,必须手动添加计时器运行循环,通过使用addTimer:forMode:方法相应的NSRunLoop对象

     

    1.

    - (void)execute {
        NSTimer *timer = [NSTimer timerWithTimeInterval:2.0 target:self selector:@selector(test) userInfo:nil repeats:YES];
        [[NSRunLoop currentRunLoop] addTimer:timer forMode:NSDefaultRunLoopMode];
        [[NSRunLoop currentRunLoop] run];
    }

    2.

    - (void)execute {
        [NSTimer scheduledTimerWithTimeInterval:2.0 target:self selector:@selector(test) userInfo:nil repeats:YES];
        //为什么在主线程不需要这句run,那是因为主线程有RunLoop而且已经启动
        [[NSRunLoop currentRunLoop] run];
    }

    这两个代码效果是一样的,scheduledTimerWithTimeInterval相当于timerWithTimeInterval的两句。

     

  • 相关阅读:
    1006 Sign In and Sign Out
    1005 Spell It Right
    1004 Counting Leaves
    1003 Emergency
    PAT甲级练习题1001、1002
    翻转字符串.
    JavaScript实现弹幕效果
    SSI技术
    c#事务处理(sqlTransaction)
    Fiddler查看接口响应时间
  • 原文地址:https://www.cnblogs.com/langji/p/5344475.html
Copyright © 2011-2022 走看看