scheduledTimerWithTimeInterval和timerWithTimeInterval的区别

原英文地址:http://blog.csdn.net/leikezhu1981/article/details/45535329

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:

一个timer对象一次只能在唯一的运行循环中注册,尽管在那个运行循环中timer对象能被添加多种运行循环模式。有三种方式创建一个timer。

  • Use the scheduledTimerWithTimeInterval:invocation:repeats: orscheduledTimerWithTimeInterval:target:selector:userInfo:repeats: class method to create the timer and schedule it on the current run loop in the default mode.

  • 运用***和&&&类方法创建timer对象,用默认的模式安排这个对象在目前的运行循环中


  • Use the timerWithTimeInterval:invocation:repeats: ortimerWithTimeInterval:target:selector:userInfo:repeats: class method to create the timer object without scheduling it on a run loop. (After creating it, you must add the timer to a run loop manually by calling the addTimer:forMode: method of the corresponding NSRunLoop object.)

  •  [[NSRunLoop currentRunLoop] addTimer:timer forMode:NSRunLoopCommonModes];

  • 应用timerwithTimeInterval:invocation :repeats或者timerWithTimeInterval:taeget:selector:userInfo:repeats类方法创建的timer对象没有安排在一个运行循环中,你必须通过运行时对象对应的方法addTimer:forMode:人为的把这个timer添加进那个运行时。

  • Allocate the timer and initialize it using theinitWithFireDate:interval:target:selector:userInfo:repeats: method. (After creating it, you must add the timer to a run loop manually by calling the addTimer:forMode: method of the corresponding NSRunLoop object.)

  • 通过initWithFireDate:interval:target:selector:userInfo:repeats:这个方法分配timer对象和初始化它,创建后,你必须人为的通过对应的运行时对象方法addTimer:forMode:把这个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 theinvalidate method returns or at some later point. Once invalidated, timer objects cannot be reused.

一旦这个timer对象安排进一个运行循环,timer对象在特定的间隔后就会执行除非它被打爆了(哈哈,就是无效了),一个非反复的timer在它执行一次后立刻就会失效了,然而,对于一个反复的方法,你必须主动通过调用它的无效方法:invalidate来打爆那个timer对象,调用那个方法就是请求把那个timer对象从那个目前的运行循环中移除。因此,你应该总是从timer被安装在的线程处调用那个”打爆“方法,“打爆”那个timer立即废了它,所以它不会影响那个运行循环。运行循环要么仅仅就在那个打残方法返回或者就是在那晚一点,运行循环于是就移除那个timer并且移除了运行时对那个timer的强引用。timer一旦被打爆,它就不能被重用了。


总而言之:scheduledTimerWithTimeInterval  会自动运行timer

而timerWithTimeInterval需要加到运行循环里面


你可能感兴趣的:(翻译文章)