tableview reloadData在解包可选值时崩溃意外发现的nil
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了tableview reloadData在解包可选值时崩溃意外发现的nil相关的知识,希望对你有一定的参考价值。
我无法理解为什么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()
}
答案
@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()
}
另一答案
为您的数据添加验证:
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)
在初始化之后还显示recipesVC
:self.present(...)
或self.navigationController?.show(...)
以上是关于tableview reloadData在解包可选值时崩溃意外发现的nil的主要内容,如果未能解决你的问题,请参考以下文章
Alamofire URL 请求 - 解包可选值时意外发现 nil