iphone - 具有整数迭代的 applicationDidEnterBackground

标签 iphone objective-c cocoa multitasking

我的问题很简单(我认为)。我有一个实现简单计时器的类(使用一些整数和 NSTimer)。我想关闭我的应用程序(因此进入后台模式),但我希望我的计时器仍然继续计数。我该如何管理?

非常感谢!

最佳答案

保存启动计时器时的时间。类似 self.timerStartDate = [NSDate date];。每秒调用一次 NSTimer 并递增一个整数将会得到非常不准确的结果。
来自 NSTimer Class Reference :

A timer is not a real-time mechanism; it fires only when one of the run loop modes to which the timer has been added is running and able to check if the timer’s firing time has passed. Because of the various input sources a typical run loop manages, the effective resolution of the time interval for a timer is limited to on the order of 50-100 milliseconds. If a timer’s firing time occurs during a long callout or while the run loop is in a mode that is not monitoring the timer, the timer does not fire until the next time the run loop checks the timer. Therefore, the actual time at which the timer fires potentially can be a significant period of time after the scheduled firing time.

如果您使用保存 startTime 的方法,如果程序未运行,您的计时器甚至会“运行”

<小时/>

编辑: 是的。用计时器来计时是错误的。
我刚刚写了一个小测试用例。具有 12 行简单表格 View 的应用程序。两个计时器,一个每毫秒触发一次,另一个每 10 秒触发一次。
在第一个计时器中,我将 1 添加到整数,在第二个计时器中,我打印第一个计时器的结果以及自上次打印以来耗时,用 mach_absolute_time() 测量。
看看差异,第一个测量结果相当不错,但如果我开始在那个简单的 UITableView 中滚动(它在我功能强大的 Mac 上的模拟器中运行),您会得到很大的差异。

2010-10-27 11:16:49.266 MutliTableTest[24726:207] Calculated: 9.988000000000
2010-10-27 11:16:49.267 MutliTableTest[24726:207] Measured  : 10.000055888000
2010-10-27 11:16:59.266 MutliTableTest[24726:207] Calculated: 9.986000000000
2010-10-27 11:16:59.267 MutliTableTest[24726:207] Measured  : 9.999898500000
2010-10-27 11:17:09.608 MutliTableTest[24726:207] Calculated: 8.091000000000
2010-10-27 11:17:09.609 MutliTableTest[24726:207] Measured  : 10.341779530000
2010-10-27 11:17:19.266 MutliTableTest[24726:207] Calculated: 1.966000000000
2010-10-27 11:17:19.267 MutliTableTest[24726:207] Measured  : 9.658319274000
2010-10-27 11:17:29.266 MutliTableTest[24726:207] Calculated: 9.991000000000
2010-10-27 11:17:29.267 MutliTableTest[24726:207] Measured  : 9.999891531000

所以不要使用 NSTimer,使用 NSDate 并使用类似 NSTimeInterval ti = [[NSDate date] timeIntervalSinceDate:self.startDate]; 来获取当前时间和 startTime 之间的差异

但我想知道为什么你需要每毫秒不同的时间戳

关于iphone - 具有整数迭代的 applicationDidEnterBackground,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4031285/

相关文章:

cocoa - 无法在现有ObjectWithID :error: 的子上下文中检索临时对象

iphone - 创建核心数据文件后出错

ios - 创建类似于联系人应用程序的操作表

ios - 无法在 Crashlytics/fabric 中获取崩溃报告。显示错误 : "It looks like we are missing dSYMs to process crashes for the versions below."

ios - UITextView 中的 UITextField?

ios - 移动 imageView 时旋转它

cocoa - 为什么 makeViewWithIdentifier :owner: return different types sporadically?

swift - 从崩溃的应用程序中停止 NSPrintOperation

ios - 如何在 Swift 中重新加载 UIPageViewController 以重新加载其 View

iphone - iPhone应用程序在添加UISwitch时崩溃