【问题标题】:Saving time in UserDefaults在 UserDefaults 中节省时间
【发布时间】: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


【解决方案1】:

这段代码对我有用:

let app = UserDefaults.standard
let date = Date()
app.set(date, forKey: "date")

if let date2 = app.object(forKey: "date") as? Date {
  Date().timeIntervalSince(date2)
}

使用更多功能(例如if letguard let 等)代替强制解包变量。这样可以避免在转换失败时使您的应用程序崩溃

【讨论】:

    【解决方案2】:

    我不建议将 Date() 保存为 UserDefaults 中的值,我会尝试使用更容易来回序列化的东西,例如字符串或整数。

    尝试替换:

    appData.set(Date(), forKey: GameData.lastTimeActiveStamp)
    

    appData.set(Date().timeIntervalSince1970, forKey: GameData.lastTimeActiveStamp)
    

    【讨论】:

    • UserDefaults 类提供了方便的方法来访问浮点数、双精度数、整数、布尔值和 URL 等常见类型。默认对象必须是一个属性列表——即,NSData、NSString、NSNumber、NSDate、NSArray 或 NSDictionary 的实例(或集合的实例组合)。 developer.apple.com/documentation/foundation/userdefaults
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-04-18
    • 1970-01-01
    • 1970-01-01
    • 2017-06-27
    • 2016-07-04
    相关资源
    最近更新 更多