Saving and loading whole code in Xcode Swift
I am trying to store an integer so it appears after switching the page or closing the game. I did this to change the number, but how do I keep this number when I switch pages and load them when I return to this page.
Change code:
@IBAction func MoneyPress(sender: AnyObject) {
Money += 1
var MoneyNumberString:String = String(format: "Dollars:%i", Money)
self.DollarsLabel.text = (string: MoneyNumberString)
}
source to share
If there is not a lot of data, the strategy I use to save the data is to pass it between pages and save it between application launches to store the value in NSUserDefaults
.
Parameter value . When you first get it or when you change data, save it to NSUserDefaults
.
@IBAction func MoneyPress(sender: AnyObject) {
Money += 1
var MoneyNumberString:String = String(format: "Dollars:%i", Money)
self.DollarsLabel.text = (string: MoneyNumberString)
let defaults: NSUserDefaults = NSUserDefaults.standardUserDefaults() //This class variable needs to be defined every class where you set or fetch values from NSUserDefaults
defaults.setObject(MoneyNumberString, forKey: "money")
defaults.synchronize() //Call when you're done editing all defaults for the method.
}
Loading a value . When you need to get values, just take it with NSUserDefaults
.
@IBAction func loadButton(sender: UIButton) {
let defaults: NSUserDefaults = NSUserDefaults.standardUserDefaults()
var money = defaults.valueForKey("money") as? String
dollarLabel.text! = money
}
To remove the stored data, all you have to do is call the removeObjectForKey function for each previously set key.
let defaults: NSUserDefaults = NSUserDefaults.standardUserDefaults()
defaults.removeObjectForKey("money")
defaults.synchronize()
Helpful source for NSUserDefaults :
NSUserDefulats
Class link: Link here .
source to share
You can use NSUserDefaults for this.
Save value
NSUserDefaults.standardUserDefaults().setInteger(money, forKey: "MoneyKey");
Get value
NSUserDefaults.standardUserDefaults().integerForKey("MoneyKey");
Thus, you can get the value in viewDidLoad
and load the data:
override func viewDidLoad()
{
super.viewDidLoad()
loadWebView()
var money = NSUserDefaults.standardUserDefaults().integerForKey("MoneyKey");
}
When you first come to the view, the value of money will be 0 .
Delete value
If you need to remove a value from NSUserdefaults
, you can use:
NSUserDefaults.standardUserDefaults().removeObjectForKey("MoneyKey")
source to share