问题
I am trying to make a simple game for IOS using xcode and swift 2. The game I would like to make is similar to "a dark room", so it does not have complicated graphic or anything really difficult.
I was not able to find \ understand how to save (and then load) the data of the progress of the game, which would include my clickcounts, arrays, textview, and some variables for the inventory. I would like to have a button "save" and a button "load".
I would also like to add that the game I am making is with the setting "simple view application" of xcode.
I am new to programming, please be detailed :)
回答1:
For a basic game you might get away with NSUserDefaults. Just create a plist file (i.e. Defaults.plist) with your settings - i.e. score, rounds, etc. and then use something like the code below to read register these defaults in your didFinishLaunchingWithOptions method in your AppDelegate.
let defaults = NSUserDefaults.standardUserDefaults()
let prefs = NSBundle.mainBundle().pathForResource("Defaults", ofType: "plist")
let dict = NSDictionary(contentsOfFile: prefs!)
defaults.setObject(dict, forKey: "defaults")
defaults.registerDefaults(dict as! [String : AnyObject])
defaults.synchronize()
Later you can read and set your defaults throughout your app by accessing:
NSUserDefaults.standardUserDefaults()
You would retrieve a value like so:
let score = NSUserDefaults.standardUserDefaults().integerForKey("score")
and set it this way:
NSUserDefaults.standardUserDefaults().setInteger(score, forKey: "score")
来源:https://stackoverflow.com/questions/37621433/how-to-save-data-of-a-game