Skip to main content
 首页 » 操作系统

ios之NSTimer 似乎被 MKMapView 平移减慢了速度

2024年01月01日68飞鱼

在 UIViewController 中,我有一个 NSTimer 计划每 1 秒触发一次,使用 scheduledTimer 方法,所以我可以更新一个 UILabel 每秒在 View 中。但问题是,每当我在 UIView 内部的 MKMapView 周围平移时,NSTimer 触发似乎被延迟。所以延迟导致 UILabel 没有统一更新,这是不好看的。 MKMapView 平移导致的延迟会占用太多资源吗?我如何安排 NSTimer 以便在平移 MKMapView 时没有延迟? (但是请注意,我没有在某种后台线程上安排 NSTimer,它在主线程中。)谢谢。

请您参考如下方法:

如果您使用 scheduledTimerWithTimeInterval(...) 创建您的计时器,它将被添加到模式为 NSDefaultRunLoopMode 的当前运行循环中。当您的应用程序忙于事件跟踪时,计时器不会触发,即如果您在 UIScrollView 中滚动或与您的 UI 进行任何其他交互。

如果您使用 NSRunLoopCommonModes 作为模式,您可以创建一个未安排的 NSTimer 并将其添加到自己的运行循环中,当您与用户界面交互时,计时器将触发。

let timer = NSTimer(timeInterval: 1.0, target: self, selector: Selector("timerFired:"), userInfo: nil, repeats: true) 
NSRunLoop.currentRunLoop().addTimer(timer, forMode: NSRunLoopCommonModes) 

更多信息,问题NSDefaultRunLoopMode vs NSRunLoopCommonModes包含关于不同运行循环模式的很好的解释。