objective-c - 在 Cocoa 应用程序中跟踪实际使用时间

标签 objective-c xcode macos cocoa trialware

灵感来自@PeterHosey 在 this question 中的有趣评论, 我决定实现使用时间跟踪系统。

喜欢:

  • 应用程序启动,计数器启动
  • 应用程序终止,记录整个持续时间
  • 在任何时候(甚至在执行期间),如果总使用时间超过允许时间,用户会收到通知

但是,我有几个...概念性问题:

  • 我要跟踪什么? [NSDate date] 就够了吗?
  • 如果用户只是在某个时候更改了他的系统日期/时间怎么办?
  • 此外,要 Hook 哪些特定的委托(delegate)方法?我的意思是,您会在哪里调用计数函数的启动/停止例程?

我洗耳恭听! :-)

最佳答案

好吧,我认为您不需要为此使用 [NSDate date] 方法。为什么不使用 mach_absolute_time() 函数?要跟踪流逝的时间,它可能是一些计时器(滴答声,例如,每分钟)。

GCD-timers 是实现计时器的一种简单灵活的方法,您可以根据需要暂停和恢复计时器(例如,如果您想在程序未使用时暂停它。)。

- (void)createTimerSource
{
  // myTimerQueue and trialTimer are class members
  myTimerQueue = dispatch_queue_create("label.yourapp.com", NULL);
  trialTimer = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0, myTimerQueue);
  dispatch_source_set_timer(m_ping_timer, dispatch_time(DISPATCH_TIME_NOW,TimerPeriod * NSEC_PER_MSEC), TimerPeriod * NSEC_PER_MSEC,NSEC_PER_SEC/10);
  // set event handler
  dispatch_source_set_event_handler(m_ping_timer,^{
      // the code to check time elapsed
   });
  // set the cancel handler 
  dispatch_source_set_cancel_handler(m_ping_timer,^{
      // release timer dispatch source
      if(trialTimer)
         dispatch_release(trialTimer);
      // release dispatch timer
      if(myTimerQueue)
         dispatch_release(myTimerQueue);
   });
  // created sources always suspended
  dispatch_resume(trialTimer); // to suspend the timer use dispatch_suspend(trialTimer)
}

关于objective-c - 在 Cocoa 应用程序中跟踪实际使用时间,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26708990/

相关文章:

ios - 同时为多个 UIView 设置动画

ios - UIApplication.sharedApplication().setStatusBarStyle() 已在 iOS 9 中弃用

ios - swift : Assets folder not working properly after recovering it back from bin

macos - Qt 创作者 : Quit previous instance of app before running again?

Android Studio 模拟器无法启动 "Waiting for target device to come online"

ios - 在一个标签字符串中显示两种不同类型的变量

objective-c - 我可以在 restkit 的异步结果中使用 block 吗?

ios - Xcode 6 Beta 6 上的 iPhone 5c 配置

iphone - 获取NSArray中xcode项目文件夹的所有图像

macos - 打开应用程序 : How to detect filename in go