我能够保存一个整数并使用NSUserdeafaults加载它,但当我加载该数字并尝试继续添加到该数字时,它从0开始。
示例:我按下按钮7次并切换到其他页面。我回去点击加载按钮,然后是第7天。当我再次点击它时,它会显示1。
这是我的"按金钱"代码:
//按金钱
@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()
defaults.setObject(MoneyNumberString, forKey: "money")
defaults.synchronize()
}
加载代码:
@IBAction func LoadTestButton(sender: UIButton) {
let defaults: NSUserDefaults = NSUserDefaults.standardUserDefaults()
var money = defaults.valueForKey("money") as? String
DollarsLabel.text! = money!
}
如果您知道如何继续添加该号码,请提供帮助。
完整代码:
import UIKit
class ViewController: UIViewController {
@IBOutlet weak var MoneyButton: UIButton!
@IBOutlet weak var OptionButton: UIButton!
@IBOutlet weak var FeelingLuckyButton: UIButton!
@IBOutlet weak var TrophiesButton: UIButton!
@IBOutlet weak var DollarsLabel: UILabel!
@IBOutlet weak var BuyNowOne: UIButton!
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.
}
var Money = Int(0)
//Press for Money
@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()
defaults.setObject(MoneyNumberString, forKey: "money")
defaults.synchronize()
}
@IBAction func LoadTestButton(sender: UIButton) {
let defaults: NSUserDefaults = NSUserDefaults.standardUserDefaults()
var money = defaults.valueForKey("money") as? String
DollarsLabel.text! = money!
}
}
答案 0 :(得分:0)
问题是,当您确实要将Money
设置为包含NSUserDefaults
中的值时,您将LoadTestButton
设置为0。要在@IBAction func LoadTestButton(sender: UIButton) {
let defaults: NSUserDefaults = NSUserDefaults.standardUserDefaults()
var money = defaults.valueForKey("money") as? String
DollarsLabel.text! = money!
// Set "Money" to contain the numbers in your "money"
// string converted to an Int
Money = money!.stringByTrimmingCharactersInSet(NSCharacterSet.decimalDigitCharacterSet().invertedSet).toInt()!
}
方法中执行此操作,请尝试以下操作:
{{1}}