Swift 2.1 – 意外地发现零,而解包一个可选的委托方法调用

我有以下两个ViewControllers(一个是TableViewController)的CategoryTableViewController有一个委托方法,将被称为表格单元格被选中时。 然后CreateRecipeViewController实现这个委托方法并处理选定的类别string。

我得到fatal error: unexpectedly found nil while unwrapping an Optional的行在线delegate.categoryController(self, didSelectCategory: categoryCell)

print(categoryCell)正确打印选定表格单元格的string值,所以我不知道为什么我得到这个错误。

我是新的执行协议,所以可能有很高的机会,我做错了。 我很感激,如果有人能给我一个线索这个错误。

CategoryTableViewController(select类别)

 protocol CategoryTableViewControllerDelegate: class { func categoryController(controller: CategoryTableViewController, didSelectCategory category: String) } class CategoryTableViewController: UITableViewController { ... weak var delegate: CategoryTableViewControllerDelegate! ... override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) { if let categoryCell = recipeCategory[indexPath.row].name { print(categoryCell) delegate.categoryController(self, didSelectCategory: categoryCell) } } } 

CreateRecipeViewController(接收选定的类别)

 extension CreateRecipeViewController: CategoryTableViewControllerDelegate { func categoryController(controller: CategoryTableViewController, didSelectCategory category: String) { let selectedCategory = category dismissViewControllerAnimated(true, completion: nil) let cell = RecipeCategoryCell() cell.configureSelectedCategoryCell(selectedCategory) recipeCategoryTableView.reloadData() } } 

UPDATE

在这里输入图像说明

问题是你忘了给属性delegate赋值。 换句话说, delegate是零。

由于delegate是隐式未变形的可选types,因此不需要添加问号或感叹号来解包它。 这就是为什么你没有看到这个错误。

为了解决这个问题,只需在delegate之后放一个问号:

 delegate?.categoryController(self, didSelectCategory: categoryCell) 

但是这并不能解决问题! 这样, categoryController(:didSelectCategory:)永远不会被调用!

不幸的是,我无法想象使用委托在视图控制器之间传递数据的方法。 但是有一个更简单的方法来做到这一点。

为了简单起见,让我们调用CategoryTableViewController 发件人CreateRecipeViewController接收者。

这是我想你想要做的。 您希望用户在发件人中select一个类别,并将所选类别传递给接收者。 所以在发件人,你需要调用performSegueWithIdentifier ,对不对?

当视图要执行一个segue时, prepareForSegue被调用。 您需要重写该方法:

 override func prepareForSegue(segue: UIStoryBoardSegue) { if segue.identifier == "your segue's identifier" { let destinationVC = segue.destinationViewController as! reciever destinationVC.selectedCategory = self.selectedCategory } } 

在上面的代码中有一些东西是未定义的。 现在我们来定义它们。

第一件事是destination.selectedCategory 。 你在接收器中添加一个属性:

 var selectedCategory: String! 

在接收者的viewDidLoad中,你可以使用这个属性来知道用户select了什么。 换句话说,数据被传递给这个属性。

第二个是self.selectedCategory 。 我们来定义一下,在发件人:

 var selectedCategory: String! 

在发送者的tableView(:didSelectRowAtIndexPath:indexPath:)中,你需要指定self.selectedCategoryselect的类别:

 self.categorySelected = recipeCategory[indexPath.row].name 

和BOOM! 而已!