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:
-
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. -
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 theaddTimer:forMode:
method of the correspondingNSRunLoop
object.) -
Allocate the timer and initialize it using the
initWithFireDate:interval:target:selector:userInfo:repeats:
method. (After creating it, you must add the timer to a run loop manually by calling theaddTimer:forMode:
method of the correspondingNSRunLoop
object.)
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的两句。