Reputation: 343
I'm making a game that has skills which each have their own level and experience depending on how much they player has trained them. It also has things like money and items stored in a bank.
Where should I save these items so that you can access it from any view controller and so that it will save when you close and open the game?
I've decided to try and use the UserDefualts but I'm not sure what I'm doing wrong.
Could someone explain if I wanted to have a variable called coins and have a label that displayed these coins starting from 0 and every time a button is clicked the coins go up by 1. Then also be able to close the game or witch views and have the coins stay the same as before it was closed?
Upvotes: 2
Views: 218
Reputation: 15512
Firstly you should define if the game data is sensitive.
If it is not sensitive, try to use NSUserDefaults
, it is a fast way to provide primitive storage for the data that you have described.
If it is and data should be protected, try to use more sophisticated ways like CoreData
and Realm
. They have a bunch of security wrappers that will not give so easy way to manage saved data.
But you also could use cool features such as iCloud, this option will give you the possibility to store and sync game data between platforms and be quite secure.
Upvotes: 1
Reputation: 965
You can create a singleton and store your data there.
class GameState {
static let shared = GameState()
var items: [Items]
var balance: Int
var level: Int
var xp: Double
func save() {
// Save to CoreData
}
}
To access it from any other class:
GameState.shared.xp = 30
GameState.shared.save()
You would of course store the data in a database, but the singleton gives you a convenient access.
Upvotes: 0