【发布时间】:2018-02-07 08:04:41
【问题描述】:
我正在开发一个小游戏。当用户进行游戏并关闭游戏时,应用程序会保存一个时间戳,这样当他返回时,它可以以秒为单位计算他离开的时间。
我的问题是,当应用重新打开时它会崩溃。我可以看到这是一个转换问题,但我尝试了各种不起作用的方法。
所以我最后的希望是 Stack Overflow。 :-)
我的代码如下: 在 AppDelegate.swift 文件中保存日期:
appData.set(Date(), forKey: GameData.lastTimeActiveStamp)
当用户重新打开应用时(仍然是 AppDelegate.swift)
GameScene().calculateTimeLeft()
最后是我的 GameScene.swift:
let timeSinceActive = appData.object(forKey: GameData.lastTimeActiveStamp)!
/* Check the difference */
let elapsedTime = Date().timeIntervalSince(timeSinceActive as! Date)
/* Convert this to seconds */
let timeSpentAwayInSeconds = Int(elapsedTime)
/* Find out how many seconds the user had left when he quitted the game */
let currentTimeLeft = appData.integer(forKey: GameData.currentTimeLeft)
/* If the time spent away is larger than the seconds there was left, the game is over */
if timeSpentAwayInSeconds > currentTimeLeft {
/* Game over */
appData.set(0, forKey: GameData.currentTimeLeft)
GameOver()
}
编辑:
忘记粘贴日志了:
Could not cast value of type '__NSCFData' (0x1b8c90f30) to 'NSDate' (0x1b8c91b10).
2017-08-29 20:16:49.533396+0200 Sleepy[929:226885] Could not cast value of type '__NSCFData' (0x1b8c90f30) to 'NSDate' (0x1b8c91b10).
【问题讨论】:
-
如果我在操场上使用您的代码的简化版本,它似乎可以正常工作。 (
appData只是UserDefaults.standard吗?) -
嗯,这确实很奇怪。是的,我只是将“appData”作为“快捷方式”:-)
-
也许你不小心用键 GameData.lastTimeActiveStamp 写了别的东西?在你写下日期之后。
-
@user2026507 - 我建议设置一个断点,让您查看从
appData.object返回的数据类型(和内容)。 -
您是否在其他地方设置
GameData.lastTimeActiveStamp以及何时重置它?
标签: swift date foundation userdefaults