我很难理解为什么reloadData()行崩溃时出现以下错误'意外发现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()
}
答案 0 :(得分: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)
初始化后显示recipesVC
:
self.present(...)
或self.navigationController?.show(...)
答案 1 :(得分:0)
@objc func receivedRecipes() {
NotificationCenter.default.post(name: NSNotification.Name(rawValue: "recipes"), object: nil, userInfo: ["data":request.recipeDetails])
}
在你的currentVC
中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()
}