prepareForSegue首先返回nil

时间:2016-08-28 00:25:04

标签: ios swift uitableview

当我离开牢房时,我得到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运行正常,没有错误。

3 个答案:

答案 0 :(得分:0)

您正在检查indexPath的部分是否为1,如果不是,它仍将执行segue。确保您的可选单元格位于第1部分(或第0部分?)并将{{1}}调用移至if语句以使其更安全。

答案 1 :(得分:0)

修正:

{{1}}

答案 2 :(得分:0)

  1. 您的代码容易出错,因为无论如何都可以执行segue 部分
  2. 获取所选项目的更好方法是在代理内部调用indexPathForSelectedRow()方法
  3. func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
        if indexPath.section == 1 {
             performSegueWithIdentifier("showIngredientInRecipe", sender: self)
        }
    }
    
    override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
        if segue.identifier == "showIngredientInRecipe" {
            //get selected item
            let indexPath = self.tableView.indexPathForSelectedRow() {
                let selectedIngredient = recipeItem.ingredients[indexPath.row]
                print("selectedIngredient \n \(selectedIngredient)")
                //segue
                let svc = segue.destinationViewController as! UINavigationController
                let destination = svc.topViewController as! IngredientDetailViewController
                destination.ingredientItem = selectedIngredient
            }
        }
    }