ios - prepareForSegue 首先返回 nil

标签 ios swift uitableview

当我从单元格中转出时,我遇到了 fatal error :在展开可选值时意外发现 nil

代码如下:

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 打印了两次。第一次为零,第二次为预期内容。如果我将 destination.ingredientItem = selectedIngredient 替换为 destination.ingredientItem = recipeItem.ingredients[0].ingredient segue 运行正常,没有错误。

最佳答案

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

关于ios - prepareForSegue 首先返回 nil,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39186963/

相关文章:

ios - 根据其包含的 UITextView 调整 UITableViewCell 的大小

ios - 下拉显示 View

ios - 导航栏未显示在 Storyboard 中,但显示在模拟器中

iphone - 如何通过旋转在圆形轨迹上移动 uiview?

swift - 初始化前被闭包捕获的变量

ios - 添加新的 Root View Controller

ios - 只允许一个 View Controller 的所有方向

ios - 在 Realm.io 的多级键路径上使用关键字 : CONTAINS, BEGINSWITH、ENDSWITH

swift - Xcode 7 如何获取文本字段输入?

ios - 如何使用 UILabel 的内容计算自定义 UITableViewCell 的高度