How to save data of a game [closed]

陌路散爱 提交于 2019-12-25 18:16:36

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!