0

I need help saving a variable well... two variables. here is my viewcontroller file.I tried NSUser but people said that it's only supposed to be used for settings user data etc.Any help is nice :) Thanks

import UIKit
var wreath = 0
var box = 0




class ViewController: UIViewController {
@IBOutlet weak var YouHaveB: UILabel!
@IBOutlet weak var YouHaveW: UILabel!

@IBAction func Wreaths(sender: AnyObject) {
    wreath += 1
    YouHaveW.text = "You Have \(wreath) Wreaths"

}
@IBAction func Boxes(sender: AnyObject) {
    box += 1
    YouHaveB.text = "You Have \(box) Boxes"
}


override func viewDidLoad() {
    super.viewDidLoad()

    // Do any additional setup after loading the view, typically from a nib.
}

override func didReceiveMemoryWarning() {
    super.didReceiveMemoryWarning()
    // Dispose of any resources that can be recreated.
}
}
j4awesome
  • 57
  • 10
  • There's nothing wrong with adding these to NSUserDefaults. – Gruntcakes May 18 '16 at 20:43
  • I tried but I didn't work :( – j4awesome May 18 '16 at 20:44
  • Then update your posting show the code that doesn't work – Gruntcakes May 18 '16 at 20:50
  • You can also consider if using the restoration api will be more appropriate: https://developer.apple.com/library/ios/featuredarticles/ViewControllerPGforiPhoneOS/PreservingandRestoringState.html – Gruntcakes May 18 '16 at 20:52
  • Could I do this without using NSUserDeaults or the api? – j4awesome May 18 '16 at 21:01
  • What have you got against defaults? ;-) Its literally just a few lines to save and the same to restore. You can save it to a file instead if you really insist on doing so. THere's no easier way then defaults and if you think you shouldn't use them then please post a link to a reference saying its bad to do so. – Gruntcakes May 18 '16 at 21:03

2 Answers2

2

To set:

let defaults = NSUserDefaults.standardUserDefaults()
defaults.setInteger(wreath, forKey: "wreath")
defaults.setInteger(box, forKey: "box")

To fetch:

let defaults = NSUserDefaults.standardUserDefaults()
if let wreath = defaults. integerForKey("wreath")
{
   // do something with wreath value here
}

if let box = defaults. integerForKey("box")
{
   // do something with box value here
}
Eugene Gordin
  • 4,047
  • 3
  • 47
  • 80
0

NSUserDefaults can be used for storing anything from the user name to user settings. It is very simple to use.

To set value simple call:

let defaults = NSUserDefaults.standardUserDefaults()
defaults.setValue(wreath, forKey: "wreaths")
defaults.setValue(box, forKey: "box")

To get these values You need to call:

let default = NSUserDefaults.standarduserDefaults()
let box = defaults.valueForKey("box")
let wreath = defaults.valueForKey("wreath")

Hope this helps. :)

bhakti123
  • 833
  • 10
  • 22