tableview reloadData在解包可选值时崩溃意外发现的nil

问题描述 投票:0回答:2

我无法理解为什么reloadData()行崩溃时出现以下错误'unjrapping optional value时意外发现nil'(另外,为什么它是可选的?)。基本上,当用户点击一个按钮时它会触发一个API请求,显示第二个VC(recipesVC),当从API检索数据时,在receivedRecipes方法(之前的VC)中我想从recipesVC(currentVC)重新加载数据我的数据是正确的传递给recipesVC,我不明白为什么reloadData()不能在同一个VC上工作。你能帮我一点帮忙吗?谢谢。

    override func viewDidLoad() {
    super.viewDidLoad()

    let recipes = Notification.Name(rawValue: "gotRecipes")
    NotificationCenter.default.addObserver(self, selector: #selector(receivedRecipes),name: recipes, object: nil)
}

@objc func receivedRecipes() {
    let recipesVC = storyboard?.instantiateViewController(withIdentifier: "recipesList") as! RecipesViewController
    recipesVC.recipesList = request.recipeDetails
    recipesVC.recipes.reloadData()
}
ios swift uitableview crash reloaddata
2个回答
0
投票
 @objc func receivedRecipes() {
     NotificationCenter.default.post(name: NSNotification.Name(rawValue: "recipes"), object: nil, userInfo: ["data":request.recipeDetails])

 } 

在你当前的VC中

override func viewDidLoad() {
    super.viewDidLoad()
    NotificationCenter.default.addObserver(self, selector: #selector(receivedRecipes(notification:)),name: NSNotification.Name(rawValue: "recipes"), object: nil)
}

 @objc func receivedRecipes(notification: Notification) {
    recipesList = notification.userInfo
    recipes.reloadData()
 }

0
投票

为您的数据添加验证:

func receivedRecipes() {
    guard let details = request.recipeDetails else { return }
    let recipesVC = storyboard?.instantiateViewController(withIdentifier: "recipesList") as! RecipesViewController
    recipesVC.recipesList = details
    recipesVC.recipes.reloadData()
}

下一个提示,您可以更新您的通知并从notification.object获取食谱,但之前您应该将它们粘贴到:

let parsedRecipes = Recipes()
NotificationCenter.default.post(name: NSNotification.Name(rawValue: "gotRecipes"), object: parsedRecipes, userInfo: nil) 

在初始化之后还显示recipesVCself.present(...)self.navigationController?.show(...)

© www.soinside.com 2019 - 2024. All rights reserved.