[英]Tracking Elapsed Time with Swift
So I a countdown timer for a task, and I want to know if there is a way to store the time that has elapsed so that it can be recorded in the app. 因此,我为一个任务设置了一个倒计时计时器,我想知道是否有一种方法可以存储已过去的时间,以便可以将其记录在应用程序中。 So for example evertyime you used the countdown timer you would store the time that the countdown was running as a lifetime value.
因此,例如,您使用倒数计时器使用evertyime时,会将倒计时运行的时间存储为生存期值。
If this exact set of instructions was repeated the total lifetime value would be 11 minutes. 如果重复此确切的指令集,则总寿命值将为11分钟。
If anyone can point me in the direction of a resource that would explain how to implement such functionality this would be greatly appreciated. 如果有人能指出我的资源方向,该资源将解释如何实现这样的功能,将不胜感激。
You have several options available to you for persisting a number like that - the absolute easiest and quickest is probably just to use UserDefaults
to store/retrieve the number. 您可以使用多个选项来保留这样的数字-绝对最简单,最快捷的选择就是使用
UserDefaults
来存储/检索数字。 That is not exactly the intended use for UserDefaults
, but if you're just storing one TimeInterval
it's not going to cause you any problems. 这不是
UserDefaults
确切用途,但是如果您仅存储一个TimeInterval
则不会造成任何问题。
A bare bones implementation would look like this: 一个简单的实现看起来像这样:
let interval: TimeInterval = 20 //replace with the time from your countdown timer
UserDefaults.standard.set(interval, forKey: "totalTimeElapsed")
And since you need to add the new time to the existing elapsed time, you would do something like this: 并且由于您需要将新时间添加到现有的经过时间中,因此您将执行以下操作:
let newTimeElapsed: TimeInterval = 20 //replace with time from countdown timer
let totalSoFar = UserDefaults.standard.double(forKey: "totalTimeElapsed") //will be 0 if it doesn't exist
UserDefaults.standard.set(newTimeElapsed + totalSoFar, forKey: "totalTimeElapsed")
Other standard ways you could do this would be NSKeyedArchiver
or Core Data
, though Core Data
would be major overkill for persisting 1 number. 您可以执行此操作的其他标准方式是
NSKeyedArchiver
或Core Data
,尽管Core Data
对于保留1个数字可能会大有作为。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.