2

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?

mkrieger1
  • 19,194
  • 5
  • 54
  • 65
Jacob Peterson
  • 343
  • 1
  • 4
  • 12
  • 1
    related http://stackoverflow.com/questions/28628225/how-to-save-local-data-in-a-swift-app – Nazmul Hasan Apr 23 '17 at 18:32
  • Definitely look at Nazmul's link. You have multiple options. NSUserDefaults is a good option if it's not a lot of data. The user's Documents directory is available if you want to store a lot of information. – Mozahler Apr 23 '17 at 18:49
  • Use NSUSerDefaults: http://stackoverflow.com/questions/25269686/swift-saving-highscore-using-nsuserdefaults – Andy Lebowitz Apr 23 '17 at 19:12
  • 'use NSuserdefaults'... NO. – J. Doe Apr 23 '17 at 21:14
  • Suggesting to use NSUserDefaults for anything other than user-facing, user-selectable options is promoting abuse of the feature – dbn Apr 27 '17 at 00:28

2 Answers2

1

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.

mkrieger1
  • 19,194
  • 5
  • 54
  • 65
Oleg Gordiichuk
  • 15,240
  • 7
  • 60
  • 100
  • Nice answer! It might also be a good idea to make sure he is aware of the MVC pattern. Besides storage, he is also worried about sharing data between VCs, which MVC solves nicely ;-) – Paulo Mattos Apr 23 '17 at 20:02
0

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.

Adam Eri
  • 889
  • 7
  • 13