iOS 应用开发建议.应用程序DidEnterBackground

问题描述:

我对 swift 很感兴趣,我正在尝试制作一个简单的游戏.我得到了一些在游戏过程中发生变化的变量.如果 applicationDidEnterBackground 以及 appDelegate 中的所有其他函数,保存这些变量的最佳做法是什么?

I´m having some fun with swift and I´m trying to make a simple game. I got a few variables that changes during the game. What´s the best practice for saving those variables if applicationDidEnterBackground and for all those other functions in appDelegate.

我认为将它们存储在核心数据中并在应用再次启动时加载它们.

What I believe is to store them in core data and load them when app starts up again.

有人对这个主题有一些经验吗?

Anyone with some experience around this theme?

如果你只想存储和管理几个变量,你可以使用 NSUserDefaults.

If its just a few variables you want to store and manage you could use NSUserDefaults.

    // Create defaults
    let defaults = NSUserDefaults.standardUserDefaults()

    // Set an int for highScoreKey in our defaults
    defaults.setInteger(10, forKey: "highScoreKey")

    // Sync/Save the defaults we've changed
    defaults.synchronize()

    // Then to retrieve our highScoreKey default we've saved
    // We create an int to store the value that is in our default
    var highScoreInt = defaults.integerForKey("highScoreKey")

    println(highScoreInt)
    // Prints 10

我会在获得需要的值后立即设置并保存这些值,而不是在 applicationDidEnterBackground 中.

I'd set and save these values as soon as I have the values I need rather than in applicationDidEnterBackground though.

NSUserDefaults 类参考