행복한개발자
행복한개발자

Reputation: 21

The reason why Unexpectedly found nil while implicitly unwrapping an Optional value

I'm making an expandable / collapse table view.

I use Storyboard. And I also checked storyboard.

There is no problem with building.

But it doesn't work on emulators.

import UIKit

class NoticeViewController: UIViewController, UITableViewDataSource, UITableViewDelegate {
    
    @IBOutlet weak var noticeTableView: UITableView!
    
    var imageArr = ["cm_contents_01", "cm_contents_02", "cm_contents_03"]
    var nameArr = ["Notice 1", "Notice 2", "Notice 3"]
    
    var selectedIndex = -1
    var isCollapce = false
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        view.backgroundColor = .white
        
        noticeTableView.estimatedRowHeight = 3000
        noticeTableView.rowHeight = UITableView.automaticDimension
    }
...

There's an error here.

noticeTableView.estimatedRowHeight = 3000

And Storyboard connection.

enter image description here

When it was made separately, it was executed well, but it is combined with other projects, so there is an error.

Unexpectedly found nil while implicitly unwrapping an Optional value

Please tell me why there is an error.

Upvotes: 0

Views: 106

Answers (1)

Glenn Posadas
Glenn Posadas

Reputation: 13283

You are making your own instance of NoticeViewController:

private let noticeController = NoticeViewController()

But you are using Storyboard too! Instead of doing that, you need to get to get properly your NoticeViewController from your Storyboard, like so:

class ViewController: UIViewController, MenuControllerDelegate {
    private var sideMenu: SideMenuNavigationController?
    
    private var noticeController: NoticeViewController?

....

override func viewDidLoad() {
    super.viewDidLoad()

    let storyboard = UIStoryboard(name: "Main", bundle: nil)
    self.noticeController = storyboard.instantiateViewController(withIdentifier: "YourControllerId"
}

and then from there, you'll have a proper instance of your NoticeViewController. The crash you are experiencing literally means the tableView object is missing (nil).

Upvotes: 1

Related Questions