我需要能够记录反应时间,从屏幕加载或问题标签刷新到用户点击数字按钮。我找不到Apple提供的有关此文档的帮助。NSDate还不够准确,我至少需要测量毫秒。mach_absolute_time似乎受到游戏设计师的青睐,因为它在内部是一致的,但不适用于此应用程序,因为我需要在设备之间比较数据,并且mach_absolute_time取决于CPU的时间。这个Apple Dev Q&A建议使用NanosecondsToAbsolute和,DurationToAbsolute但是它在obj- c中,我找不到快速的等效文档。
NSDate
mach_absolute_time
NanosecondsToAbsolute
DurationToAbsolute
是否有一个快速的版本NanosecondsToAbsolute,并DurationToAbsolute说我只是没有找到?其他一些方法可以一致地做到这一点?
这是我要添加时间的代码:
class EmotionQuestionsViewController: UIViewController{ override func viewDidLoad() { super.viewDidLoad() //mark "startTime" when view loads } @IBOutlet var questionLabel: UILabel! var timeResultsStack = [String]() var questionsStack = ["HAPPY", "ANXIOUS"] var questionResultsStack = [String]() var questionStackArrayIndex = 1 @IBAction func RecordValueFromNumericalScaleOneToSeven(sender: UIButton) { //mark durration time as currentTime - startTime, append to timeResultsStack let value = sender.currentTitle! questionResultsStack.append(value) if questionResultsStack.count < questionsStack.count{ self.questionLabel.text = "how \(questionsStack[questionStackArrayIndex]) are you right now?" //mark startTime when label is changed self.questionStackArrayIndex++ } else{ self.performSegueWithIdentifier("showResults", sender: nil) } }
您可以使用NSTimeInterval来测量时间(比计时器好得多)。您只需要存储两个日期(两个时间点)并减去endTime- StartTime即可,如下所示:
import UIKit class ViewController: UIViewController { var startTime: TimeInterval = 0 var endTime: TimeInterval = 0 override func viewDidLoad() { super.viewDidLoad() startTime = Date().timeIntervalSinceReferenceDate } @IBAction func stopTimeAction(_ sender: Any) { endTime = Date().timeIntervalSinceReferenceDate print((endTime-startTime).time) } }
extension TimeInterval { var time: String { .init(format: "%d:%02d:%02d.%03d", Int(self/3600), Int((self/60).truncatingRemainder(dividingBy: 60)), Int(truncatingRemainder(dividingBy: 60)), Int((self*1000).truncatingRemainder(dividingBy: 1000))) } }