我正在享受 swift 的乐趣,并且正在尝试制作一个简单的游戏。我得到了一些在游戏过程中发生变化的变量。如果出现以下情况,保存这些变量的最佳实践是什么applicationDidEnterBackground
对于所有其他功能appDelegate
.
我的想法是将它们存储在核心数据中,并在应用程序再次启动时加载它们。
有人对这个主题有一些经验吗?
如果您只想存储和管理几个变量,您可以使用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
though.
NSUserDefaults 类参考 https://developer.apple.com/library/mac/documentation/Cocoa/Reference/Foundation/Classes/NSUserDefaults_Class/index.html
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)