问题描述
我在玩弄一些快速游戏,我正在尝试制作一个简单的游戏.我得到了一些在比赛中会发生变化的变量.在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.
这篇关于有关iOS应用开发的建议. ApplicationDidEnterBackground的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!