iOS应用程序开发建议。 ApplicationDidEnterBackground

时间:2015-05-19 16:49:32

标签: ios swift appdelegate

我和swift玩得很开心,我正在尝试制作一款简单的游戏。我得到了一些在游戏过程中发生变化的变量。保存这些变量的最佳做法是current以及applicationDidEnterBackground中的所有其他功能。

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

对这个主题有一定经验的人?

2 个答案:

答案 0 :(得分:1)

如果只想存储和管理几个变量,可以使用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

NSUserDefaults Class Reference

答案 1 :(得分:0)

当我开始使用iOS编程时,我首先将数据存储在自定义文本文件中。然后我将数组保存到磁盘,使用NSUserDefaults和其他工具。最后,我决定转移到CoreData,因为我必须保存越来越多的数据,而我的应用程序变得太慢了。

回顾一下,如果我从一开始就使用CoreData会好得多。它功能非常强大,以后迁移到CoreData需要花费很多时间。

如果您想使用CoreData,我建议您先阅读一本好的教程或一本好书。我喜欢这本书"学习CoreData for iOS"作者:Tim Roadley。

一个有趣的替代方案可能是Realm。我还没有使用它,但它可能值得一看。

但是,这实际上取决于您的应用程序。如果您不需要保存大量数据,则更简单的方法就足够了(NSUserDefaults等)。

提醒:Apple建议持续保存数据,而不要等到应用程序进入后台状态。届时,该应用可能会在任何时候暂停,您无法确定您的数据是否会及时保存。