我正在尝试从 View Controller 2 检索保存在模型文件中的数据,但得到的结果为零。如何从项目中的任何 View Controller 保存和检索模型类中的数据?
模型.swift:
class Model {
var hoursTaken = 0.0
var currentGPA = 0.0
//var classArray: [String]
func saveGPA(GPA: Double) {
currentGPA = GPA
}
func returnGPA() -> Double {
return currentGPA
}
func saveHoursTaken(HoursTaken: Double) {
hoursTaken = HoursTaken
}
}
在 View Controller 1 中:
var model = Model()
func pickerView(_ pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) {
if pickerView.tag == 1 {
let hourstaken = Double(choices[row])
print(hourstaken!)
hoursTakenText.text = choices[row]
model.saveHoursTaken(HoursTaken: hourstaken!)
//print(model.hoursTaken)
}
else if row < 12 {
let currentGPA = Double(choices2[row])
print(currentGPA!)
model.saveGPA(GPA: currentGPA!)
GPATextField.text = choices2[row]
}
subView.isHidden = true
subview2.isHidden = true
}
在 View Controller 2 中打印 0.0:
import Foundation
import UIKit
class ThirdViewController: UIViewController {
var model = Model()
@IBAction func testButton(_ sender: UIButton) {
print("Test Button Pressed")
let a = model.returnGPA()//prints 0.0
print(a)
}
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.
}
}
最佳答案
如果您想从任何地方保存和检索模型类中的数据。我认为您可以在 Model 类的属性和方法之前使用 static
/class
关键字:
class Model {
static var hoursTaken = 0.0
static var currentGPA = 0.0
class func saveGPA(GPA: Double) {
currentGPA = GPA
}
class func returnGPA() -> Double {
return currentGPA
}
class func saveHoursTaken(HoursTaken: Double) {
hoursTaken = HoursTaken
}
}
在 View Controller 1 中:
// var model = Model() // Remove this line
func pickerView(_ pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) {
if pickerView.tag == 1 {
let hourstaken = Double(choices[row])
hoursTakenText.text = choices[row]
Model.saveHoursTaken(HoursTaken: hourstaken!)
} else if row < 12 {
let currentGPA = Double(choices2[row])
GPATextField.text = choices2[row]
Model.saveGPA(GPA: currentGPA!)
}
subView.isHidden = true
subview2.isHidden = true
}
在 View Controller 2 中:
// var model = Model() // Remove this line
@IBAction func testButton(_ sender: UIButton) {
let a = Model.returnGPA()
}
关于swift - 如何检索保存在模型类 Swift 3 中的数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45224281/