NSTimer和NSRunLoop

ran*_*dom 6 objective-c nstimer nsrunloop cllocationmanager

我的应用跟踪用户CLLocationManager.在委托电话中,didUpdateToLocation我做了所有有趣的事情来保存他们的位置.但是,我需要一种方法来测试它们是否已停止.我可以停止记录位置并考虑他们的旅行.所以我有一个NSTimerCCLocationManager那个被添加,每次取出didUpdateToLocation被调用.当用户停止并CLLocationManager停止被叫时,它将被启动.

我能够完成NSTimer工作的唯一方法是:

[[NSRunLoop mainRunLoop] addTimer:userStoppedMovingTimer forMode:NSRunLoopCommonModes];
Run Code Online (Sandbox Code Playgroud)

然后删除它:

[userStoppedMovingTimer invalidate];
Run Code Online (Sandbox Code Playgroud)

我以前从来没有像这样添加计时器.有人可以解释为什么会这样吗?

Tom*_*ing 8

文档:

有三种方法可以创建计时器:

  1. 使用scheduledTimerWithTimeInterval:invocation:repeats:or scheduledTimerWithTimeInterval:target:selector:userInfo:repeats:class方法创建计时器并在默认模式下在当前运行循环上计划它.

  2. 使用timerWithTimeInterval:invocation:repeats:or timerWithTimeInterval:target:selector:userInfo:repeats:class方法创建计时器对象,而不在运行循环上计划它.(创建它之后,必须通过调用addTimer:forMode:相应NSRunLoop对象的方法手动将计时器添加到运行循环中.)

  3. 分配计时器并使用该initWithFireDate:interval:target:selector:userInfo:repeats:方法对其进行初始化 .(创建它之后,必须通过调用addTimer:forMode:相应NSRunLoop 对象的方法手动将计时器添加到运行循环中.)

您之前可能正在使用选项1,现在您正在使用选项2或3.