菜鸟教程小白 发表于 2022-12-11 17:23:11

ios - prepareForSegue 首先返回 nil


                                            <p><p>我收到 <code>fatal error: unexpectedly found nil while unwrapping an Optional value</code> 当我从单元格中分离出来时。</p>

<p>代码如下:</p>

<pre><code>func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
    if indexPath.section == 1 {
      let listIngredients = recipeItem.ingredients
      selectedIngredient = listIngredients.ingredient
    }
    tableView.deselectRowAtIndexPath(indexPath, animated: false)
    performSegueWithIdentifier(&#34;showIngredientInRecipe&#34;, sender: self)


}

override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
    if segue.identifier == &#34;showIngredientInRecipe&#34; {
      let svc = segue.destinationViewController as! UINavigationController
      let destination = svc.topViewController as! IngredientDetailViewController

      destination.ingredientItem = selectedIngredient


      print(&#34;selectedIngredient \n \(selectedIngredient)&#34;)

    }

}
</code></pre>

<p>这是我从调试器中得到的:</p>

<pre><code>      selectedIngredient
      nil

      selectedIngredient
      Optional(Ingredient {
            name = Rye Whiskey;
            inStock = 1;
            type = IngredientType {
                name = Spirit;
            };
      })

      fatal error: unexpectedly found nil while unwrapping an Optional value
</code></pre>

<p>如您所见,<code>selectedIngredient</code> 打印了两次。第一次为 nil,第二次为预期内容。如果我将 <code>destination.ingredientItem = selectedIngredient</code> 替换为 <code>destination.ingredientItem = recipeItem.ingredients.ingredient</code> 则 segue 运行良好且没有错误。</p></p>
                                    <br><hr><h1><strong>Best Answer-推荐答案</ strong></h1><br>
                                            <p><p>您正在检查 indexPath 的部分是否为 1,如果不是,它仍将执行 segue。确保您的可选单元格位于第 1 节(或第 0 节?)并将您的 <code>performSegueWithIdentifier("showIngredientInRecipe", sender: self)</code> 调用移动到 if 语句以使其更安全。</p></p>
                                   
                                                <p style="font-size: 20px;">关于ios - prepareForSegue 首先返回 nil,我们在Stack Overflow上找到一个类似的问题:
                                                        <a href="https://stackoverflow.com/questions/39186963/" rel="noreferrer noopener nofollow" style="color: red;">
                                                                https://stackoverflow.com/questions/39186963/
                                                        </a>
                                                </p>
                                       
页: [1]
查看完整版本: ios - prepareForSegue 首先返回 nil