Search code examples
iosswiftxcodeuisearchbariboutlet

SearchBar connected with storyboard is nil


I'm using Xcode 9.0.

My problem is easy: I dropped a UISearchBar object within a TableViewController. I connected this mySearchBar as an IBOutlet to the TableViewController class:

   class MyTableViewController: UITableViewController, UISearchBarDelegate, UINavigationControllerDelegate {

    @IBOutlet weak var mySearchBar: UISearchBar!
    @IBOutlet var myTableView: UITableView!
}
override func viewDidLoad() {
    super.viewDidLoad()

    navigationController?.delegate = self

    self.mySearchBar.delegate = self // EXC_BREAKPOINT HERE
    self.myTableView.delegate = self

    self.myTableView.backgroundColor = UIColor.init(red: 0.0/255.0, green: 60.0/255.0, blue: 113.0/255.0, alpha: 1.0)
}

The circle to the left is filled - so I'm sure the object is connected properly. When I run the project it stops at the line above, withe the error message:

fatal error: unexpectedly found nil while unwrapping an Optional value.

I tried to:

  • clean the project and rebuild
  • delete derivedData, clean and rebuild
  • delete UIsearchBar object in StoryBoard, drop a new one and reconnect as IBOutlet
  • destroy the controller in StoryBoard and recreate a brand new one.

I have no idea to go on. Any help appreciated. I know you can!

EDIT: here a screenshot with the Connections Inspector:enter image description here

EDIT2: Filtro Localita T is my TableViewController as you can see in this second screenshot enter image description here


Solution

  • I solved it. The problem was in pushing to this controller. Instead of:

    let destinationView = FiltroLocalitaTableViewController()
    destinationView.palina = self.transito.palina
    self.navigationController?.pushViewController(destinationView, animated: true)
    

    I used:

    let filtroLocalitaVC = UIStoryboard(name: "Main", bundle: nil).instantiateViewController(withIdentifier: "filtroLocalitaView") as! FiltroLocalitaTableViewController
    filtroLocalitaVC.palina = self.transito.palina
    filtroLocalitaVC.delegate = self
    self.navigationController?.pushViewController(filtroLocalitaVC, animated: true)
    

    and it worked.