Search code examples
iosswiftnsdictionarynsuserdefaultssaving-data

How to create an NSDictionary and Write and Read the information from a NSUserDefaults object in swift


I want to store 3 variables all of type Int for a game (gameLevel,time,clicks). I want to save the values of these variables in one UIViewController at the end of the game, and pass it to another UIViewController that will present the gameScore (using UILabel).

Should I use an NSDictionary object for this task? and how do I create an NSUserDefaults object and pass it the NSDictionary?


Solution

  • Save the values in NSUserDefaults when game ends

    NSUserDefaults.standardUserDefaults().setInteger(gameLevel, forKey: "gameLevelKey")
    NSUserDefaults.standardUserDefaults().setInteger(time, forKey: "timeKey")
    NSUserDefaults.standardUserDefaults().setInteger(clicks, forKey: "clicksKey")
    NSUserDefaults.standardUserDefaults().synchronize()
    

    Get the saved values from NSUserDefaults in other view controller

    let gameLevel = NSUserDefaults.standardUserDefaults().integerForKey("gameLevelKey")
    let time = NSUserDefaults.standardUserDefaults().integerForKey("timeKey")
    let clicks = NSUserDefaults.standardUserDefaults().integerForKey("clicksKey")
    



    NSUserDefaults is like database where you can save values using setXXX method and retrieve values using the xxxForKey method