用户默认未在主视图控制器中更新



我正在创建一个简单的计数器应用程序,用户可以在其中设置其营业场所允许的最大顾客数量,当达到该数量时,他们会收到通知,告知他们处于最大容量。我正在使用UserDefaults来存储此数据,但是每当我更新设置中的最大数字并返回主视图时,它仍然使用以前的最大数字。如果我关闭应用程序并重新打开它,它的数据是正确的。如何确保数据在主视图控制器中更新,以便接收正确的数据?

法典

视图控制器.swift(主视图控制器)

import UIKit
import AVFoundation
class ViewController: UIViewController {


var counter = 0;
var max = UserDefaults.standard.integer(forKey: "max");


// Max patron alert function
func showAlert() {
let alertController = UIAlertController(title: "Limit Reached", message: "Your place of business has reached maximum capacity, please stop patrons from entering until capacity dissipates.", preferredStyle: .alert)
alertController.addAction(UIAlertAction(title: "Dismiss", style: .default))

self.present(alertController, animated: true, completion: nil)
AudioServicesPlaySystemSound(kSystemSoundID_Vibrate)
}
@IBOutlet weak var count: UILabel!

@IBAction func increment(_ sender: UIButton) {

if counter < max {
counter += 1;
count?.text = String(counter);
}


if counter == max {
showAlert();
}
}


@IBAction func decrement(_ sender: UIButton) {
if (counter == 0) {
counter += 0;
}
else {
counter -= 1;
}
count?.text = String(counter);
}

@IBAction func reset(_ sender: UIButton) {
counter = 0;

count?.text = String(counter);
}

override func viewDidLoad() {
super.viewDidLoad()
//        UserDefaults.standard.synchronize()
// Do any additional setup after loading the view.
}

override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}

设置视图控制器.swift


import UIKit

class SettingsViewController: UIViewController {

var mainViewController:ViewController?;
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
}

@IBOutlet weak var maxOccupancy: UITextField!

@IBAction func save(_ sender: UIButton) {
let max = Int(maxOccupancy.text!);

UserDefaults.standard.set(max, forKey: "max")
UserDefaults.standard.synchronize()
print(UserDefaults.standard.integer(forKey: "max"))
}



/*
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
// Get the new view controller using segue.destination.
// Pass the selected object to the new view controller.
}
*/
}

这一行:

var max = UserDefaults.standard.integer(forKey: "max")

仅在创建ViewController时执行一次。(顺便说一句:在 Swift 中不需要分号)。无论之后UserDefaults发生什么,都不会反映在其价值中。

将该行替换为

var max: Int {
UserDefaults.standard.integer(forKey: "max")
}

这样每次访问它实际上都会出去从UserDefaults获取值。

这些构造称为"计算属性",在此处进行说明。

发生这种情况是因为您在分配计数器编号时只读取一次计数器号ViewController。当屏幕上出现ViewController时,您可以尝试重新阅读它:

override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
max = UserDefaults.standard.integer(forKey: "max")
}

此外,无需在每行结尾使用;,Swift 不需要它。

最新更新