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 <
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
I'd set and save these values as soon as I have the values I need rather than in applicationDidEnterBackground
though.
NSUserDefaults Class Reference
When I started with iOS programming, I first stored data in custom text files. Then I saved arrays to disk, used NSUserDefaults
, and other tools. At the end, I decided to move to CoreData since I had to save more and more data and my application was becoming too slow.
Looking back, it would have been much better if I had used CoreData from the beginning. It is very powerful and migrating to CoreData later takes a lot of time.
If you would like to use CoreData, I recommend to start with a good tutorial or a good book. I liked the book "Learning CoreData for iOS" by Tim Roadley.
An interesting alternative may be Realm. I haven't used it yet but it may be worth a look.
However, it really depends on your application. If you do not need to save a lot of data, simpler approaches may be sufficient (NSUserDefaults, etc.).
A word of caution: Apple recommends to save data continuously and not wait until the app enters into the background state. At that time, the app may be suspended at any time and you cannot be sure that your data will be saved in time.