0

I try to create table view and search bar programmatically like that:

class SearchViewController: UIViewController  {

    weak var tableView: UITableView!
    weak var srchBar: UISearchBar!


    override func viewDidLoad() {
        super.viewDidLoad()
        self.createUserInterface()
        self.createConstraints()

    }

    func createUserInterface (){

        self.tableView = UITableView ()
//        tableView.dataSource = self
//        tableView.delegate = self
        self.view.addSubview(tableView)

        self.srchBar = UISearchBar()
        self.view.addSubview(self.srchBar)
    }



    func createConstraints () {

        tableView.snp.makeConstraints { (make) in

            make.top.equalTo(srchBar.snp.bottom)
            make.left.right.bottom.equalTo(self.view)
        }

        srchBar.snp.makeConstraints { (make) in
            make.top.left.right.equalTo(self.view)
        }

    }

Unfortunatelly, i got an error in console:fatal error: unexpectedly found nil while unwrapping an Optional value

And error like that: enter image description here

Evgeniy Kleban
  • 6,794
  • 13
  • 54
  • 107

1 Answers1

1

You're getting this error because the srchBar variable is declared as weak.

Since weak variables don't increment the retain count, it gets deallocated before you can add it as a subview.

Something like

let searchBar = UISearchBar()
view.addSubview(searchBar)
self.srchBar = searchBar

should avoid the crash.

Kaan Dedeoglu
  • 14,765
  • 5
  • 40
  • 41
  • thanks, but isn't that vars belong to superview? Why is them deallocated? – Evgeniy Kleban Feb 18 '17 at 17:52
  • they do, but you declare `self.srchBar = UISearchBar()` before adding it to the superview. So it get's deallocated before you can add it as a subview. – Kaan Dedeoglu Feb 20 '17 at 09:23
  • in Obj-C you always allocate objects before add them, in other case, how can i add to view non-existing object? – Evgeniy Kleban Feb 20 '17 at 09:23
  • What I mean is you create the object and assign it to a weak property, which makes it deallocate immediately. So you end up adding nil as a subview. – Kaan Dedeoglu Feb 20 '17 at 10:21
  • when we do let searchBar = UISearchBar() isnt we create and allocate new object in memory? – Evgeniy Kleban Feb 20 '17 at 10:25
  • yes when you do let searchBar = UISearchBar(), it's allocated and has a reference count of one until the method scope ends. But when you do self.srchBar = UISearchBar(), the reference count is never incremented (it stays at 0) because srch bar is declared as a weak variable, the object is allocated immediately after allocation. I suggest you read about how reference counting and ARC works in iOS. – Kaan Dedeoglu Feb 20 '17 at 10:32