委托=自我导致线程1:致命错误:展开一个可选值时意外发现nil

时间:2019-02-09 08:46:06

标签: ios swift delegates

countrySearch.delegate = self行给了我一个致命错误。

  

“线程1:致命错误:展开一个可选值时意外发现nil”

我的代码:

var searchedCountry = [String]()
var searching = false
@IBOutlet weak var countrySearch: UISearchBar!
@IBOutlet weak var tblView: UITableView!
override func viewDidLoad() {
    super.viewDidLoad()
    **countrySearch.delegate = self**
    // Do any additional setup after loading the view, typically from a nib.
}

override func didReceiveMemoryWarning() {
    super.didReceiveMemoryWarning()
    // Dispose of any resources that can be recreated.
}
}

extension ViewController: UITableViewDelegate, UITableViewDataSource {

  func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    if searching {
        return searchedCountry.count
    } else {
        return countryNameArr.count
    }
  }

  func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCell(withIdentifier: "cell")
    if searching {
        cell?.textLabel?.text = searchedCountry[indexPath.row]
    } else {
        cell?.textLabel?.text = countryNameArr[indexPath.row]
    }
    return cell!
  }

}

extension ViewController: UISearchBarDelegate {

  func searchBar(_ searchBar: UISearchBar, textDidChange searchText: String) {
    searchedCountry = countryNameArr.filter({$0.lowercased().prefix(searchText.count) == searchText.lowercased()})
    searching = true
    tblView.reloadData()
  }

  func searchBarCancelButtonClicked(_ searchBar: UISearchBar) {
    searching = false
    searchBar.text = ""
    tblView.reloadData()
  }

}

1 个答案:

答案 0 :(得分:0)

您的countrySearch插座未与情节提要板连接。由于未连接,控制器将countrySearch加载为nil实例,并尝试将委托设置为nil实例,因此应用程序崩溃。