我收到 fatal error: unexpectedly found nil while unwrapping an Optional value 当我从单元格中分离出来时。
代码如下:
func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
if indexPath.section == 1 {
let listIngredients = recipeItem.ingredients[indexPath.row]
selectedIngredient = listIngredients.ingredient
}
tableView.deselectRowAtIndexPath(indexPath, animated: false)
performSegueWithIdentifier("showIngredientInRecipe", sender: self)
}
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
if segue.identifier == "showIngredientInRecipe" {
let svc = segue.destinationViewController as! UINavigationController
let destination = svc.topViewController as! IngredientDetailViewController
destination.ingredientItem = selectedIngredient
print("selectedIngredient \n \(selectedIngredient)")
}
}
这是我从调试器中得到的:
selectedIngredient
nil
selectedIngredient
Optional(Ingredient {
name = Rye Whiskey;
inStock = 1;
type = IngredientType {
name = Spirit;
};
})
fatal error: unexpectedly found nil while unwrapping an Optional value
如您所见,selectedIngredient 打印了两次。第一次为 nil,第二次为预期内容。如果我将 destination.ingredientItem = selectedIngredient 替换为 destination.ingredientItem = recipeItem.ingredients[0].ingredient 则 segue 运行良好且没有错误。
Best Answer-推荐答案 strong>
您正在检查 indexPath 的部分是否为 1,如果不是,它仍将执行 segue。确保您的可选单元格位于第 1 节(或第 0 节?)并将您的 performSegueWithIdentifier("showIngredientInRecipe", sender: self) 调用移动到 if 语句以使其更安全。
关于ios - prepareForSegue 首先返回 nil,我们在Stack Overflow上找到一个类似的问题:
https://stackoverflow.com/questions/39186963/
|