我遇到了xcode的问题,因为我已更新到8.3.3。我通常使用MCV(模型 - 视图 - 控制器)方法,现在,我的变量不在它们之间更新。Xcode 8.3.3 Swift 3 - 变量不在文件之间更新
情况:我有一个模型(存储所有主要变量和计算函数);一个TableView控制器(Control Tableview)和TableViewCell(设置Outlet和操作)
目标:当在单元格中按下按钮时,它应该在TableView中添加一行。
问题:为什么表视图无法获取Model()变量的新值。
,使其更好地了解,这里是正在发生的事情的时间表:)
运行>在TableViewController运行viewDidLoad中>更新模型变量测试(> cellForRowAt被调用并打印[“1”] > show tableView with 1 row>按下按钮> print [“1”]>向Model()> print [“1”,“2”]添加[“2”]>>通知> viewDidLoad获取通知并打印“ “> cellForRowAt被调用并打印[”1“]> tableView保持1行。
这里是我的代码一个例子:
我有我的Model.Swift:
class Model {
var test : [String] = []
}
我TableViewController:
class BudgetTableViewController: UITableViewController {
let model = Model()
override func viewDidLoad() {
super.viewDidLoad()
model.test.append("1")
center.addObserver(forName: NSNotification.Name(rawValue: "reloadTableVIew"), object: appDelegate, queue: queue) {[unowned self] (_) in
print("reloading table")
self.tableView.reloadData()
}
}
为了简化..在第I回头率“ 1“,对于行,我在Model()中计算变量测试。
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
print(model.test) // **ALWAYS PRINT ["1"]**
let cell = tableView.dequeueReusableCell(withIdentifier: "buttonCell", for: indexPath) as! TableViewCell
return Cell
}
而且我TableViewCell:
class TableViewCell: UITableViewCell{
let model = BudgetModel()
let notification = Notification(name: Notification.Name(rawValue: "reloadTableVIew"), object: appDelegate)
@IBAction func okButton(_ sender: UIButton) {
print(model.test)
model.test.append("2")
print(model.test)
NotificationCenter.default.post(notification)
}
}
我希望这是非常明显的。 问题是,如果我按下按钮5次,它会向数组添加5次字符串(在打印中确认),但是当调用cellForRowAt时,它总是会打印[“1”]。
感谢您的帮助
谢谢!这工作完美!我正在寻找避免使用通知的方式!这恰好适合! –