0

I am see below error at the line "tableView.delegate = self" - EXC_BAD_INSTRUCTION (code=EXC_1386_INVOP, subside0x0). Unable to figure out what is causing the issue. I have a simple Table View with Search Bar Storyboard.

import UIKit

class ViewController: UIViewController, UITableViewDataSource, UITableViewDelegate, UISearchBarDelegate{

@IBOutlet weak var searchBar: UISearchBar!
@IBOutlet weak var tableView: UITableView!


var searchActive : Bool = false
var data = ["San Francisco","New York","San Jose","Chicago","Los Angeles","Austin","Seattle"]
var filtered:[String] = []

override func viewDidLoad() {
    super.viewDidLoad()

    /* Setup delegates */
    tableView.delegate = self **//Error thrown here**
    tableView.dataSource = self
    searchBar.delegate = self

}

func searchBarTextDidBeginEditing(_ searchBar: UISearchBar) {
    searchActive = true;
}

func searchBarTextDidEndEditing(_ searchBar: UISearchBar) {
    searchActive = false;
}

func searchBarCancelButtonClicked(_ searchBar: UISearchBar) {
    searchActive = false;
}

func searchBarSearchButtonClicked(_ searchBar: UISearchBar) {
    searchActive = false;
}

func searchBar(_ searchBar: UISearchBar, textDidChange searchText: String) {

    filtered = data.filter({ (text) -> Bool in
        let tmp: NSString = text as NSString
        let range = tmp.range(of: searchText, options: NSString.CompareOptions.caseInsensitive)
        return range.location != NSNotFound
    })
    if(filtered.count == 0){
        searchActive = false;
    } else {
        searchActive = true;
    }
    self.tableView.reloadData()
}

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


func numberOfSectionsInTableView(tableView: UITableView) -> Int {
    return 1
}

func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    if(searchActive) {
        return filtered.count
    }
    return data.count;
}

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCell(withIdentifier: "Cell")! as UITableViewCell;
    if(searchActive){
        cell.textLabel?.text = filtered[indexPath.row]
    } else {
        cell.textLabel?.text = data[indexPath.row];
    }

    return cell;
 }
}
dacscan3669
  • 651
  • 2
  • 8
  • 16

0 Answers0