1
我試圖從視圖控制器2中檢索保存在模型文件中的數據,但我得到零。如何從我的項目中的任何View Controller中保存和檢索Model類中的數據?如何檢索保存在模型類中的數據Swift 3
Model.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
}
}
在視圖控制器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
}
在視圖控制器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.
}
}
@jean:在'Model'類中,如果聲明'hourTaken'和'currentGPA'是公共變量,那麼爲什麼我們需要添加'saveGPA','returnGPA'和'saveHoursTaken'函數?爲什麼不直接訪問'hourTaken'和'curentGPA'? –
非常感謝,我會試試! – jean
它也可以使用數組嗎?我需要稍後補充。 – jean