xcode Swift-获取自计时器启动以来经过了多少秒/毫秒

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/26639856/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-15 06:02:35  来源:igfitidea点击:

Swift- Get how much sec/millisecond passes since timer started

iosxcodeswifttimernstimer

提问by Roi Mulia

trying to figure out how to get the time passed since timer started. this is what i did : Feel free to suggest other ways to get the time passed since the page loaded

试图弄清楚如何让计时器启动后的时间过去。这就是我所做的: 随意建议其他方法来获得自页面加载以来的时间

Declared timer :

声明的计时器:

 var runner = NSTimer()
 runner = NSTimer.scheduledTimerWithTimeInterval(0.6, target: self, selector: Selector("time"),      userInfo: nil, repeats: true)

Than tried this in the function,returns the interval i set(obviously)

比在函数中尝试这个,返回我设置的间隔(显然)

  func time() {

        println(self.runner.timeInterval)
    }

anyway if getting how much time passes since it started? (it's in the didload section so it like saying how much time passes since the page loaded). thanks ! :D

无论如何,如果自开始以来已经过去了多少时间?(它在 didload 部分,所以它就像说自页面加载以来经过了多少时间)。谢谢 !:D

回答by Steve Rosenberg

Put this in a playground. I added the loop just to create a time lag. Time in seconds down to fractions of a second.

把它放在操场上。我添加了循环只是为了创建时间延迟。以秒为单位的时间到几分之一秒。

var startTime = NSDate.timeIntervalSinceReferenceDate()
var currentTime: NSTimeInterval = 0

for var i = 0; i < 10000; i++ {
    if i == 99 {
        currentTime = NSDate.timeIntervalSinceReferenceDate()
        println(i)
    }

}
var elapsedTime = currentTime - startTime
println(Double(elapsedTime))

From: https://developer.apple.com/library/ios/documentation/Cocoa/Reference/Foundation/Classes/NSDate_Class/#//apple_ref/occ/instp/NSDate/timeIntervalSinceReferenceDate

来自:https: //developer.apple.com/library/ios/documentation/Cocoa/Reference/Foundation/Classes/NSDate_Class/#//apple_ref/occ/instp/NSDate/timeIntervalSinceReferenceDate

timeIntervalSinceReferenceDate

Returns the interval between the date object and January 1, 2001, at 12:00 a.m. GMT. (in seconds)

返回日期对象与 2001 年 1 月 1 日格林威治标准时间上午 12:00 之间的间隔。(片刻之间)

The method is establishing a startTime whenever you want to start. It is a time in seconds since the reference. Later we set the currentTime to be equal to the new time since the reference time. Subtracting one from the other gives elapsed time. There is several decimal place precision.

该方法是在您想要开始时建立一个 startTime。这是自参考以来的时间(以秒为单位)。稍后我们将 currentTime 设置为自参考时间以来的新时间。从另一个中减去一个给出经过的时间。有几个小数位精度。