当我尝试向mainArray添加一些值时,会出现此错误。这是MainViewController
class ViewController: UIViewController, UITableViewDataSource, UITableViewDelegate {
var mainArray:[TaskModel] = []
这是addTaskViewController
var mainVC: ViewController!
@IBAction func addBarButtonPressed(sender: UIBarButtonItem) {
var newTask = TaskModel(value: self.taskTextField.text)
mainVC.mainArray.append(newTask)
}
错误是告诉您可选项为nil-根据我在代码中看到的内容,我认为这个属性:
var mainVC: ViewController!
尚未正确初始化,这意味着它为零
感谢您的回答,我通过以下函数修复它:
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
if segue.identifier == "AddViewControllerSegue" {
let addTaskVC:AddViewController = segue.destinationViewController as AddViewController
addTaskVC.mainVC = self
}
}
然后我添加到我的addButton:
@IBAction func addBarButtonPressed(sender: AnyObject) {
var newTask = TaskModel(value: taskTextField.text)
mainVC.mainArray.append(newTask)
self.navigationController?.popViewControllerAnimated(true)
}
而且效果很好!:)