Search code examples
iosswiftuitableviewcrashreloaddata

tableview reloadData crashes unexpected found nil while unwrapping optional value


I'm having some trouble understanding why the reloadData() line crashes with the following error 'unexpected found nil while unwrapping optional value'(also, why is it an optional?). Basically, when user taps a button it fires an API request, second VC(recipesVC) is shown and when data is retrieved from the API, in receivedRecipes method (previous VC) I want to reloadData from recipesVC (currentVC) As my data is correctly passed to recipesVC, I don't see why reloadData() won't work on the same VC. Could you please give me a little help with this? thank you.

    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()
}

Solution

  •  @objc func receivedRecipes() {
         NotificationCenter.default.post(name: NSNotification.Name(rawValue: "recipes"), object: nil, userInfo: ["data":request.recipeDetails])
    
     } 
    

    In your 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()
     }