P.Festus P.Festus - 1 month ago 13
Swift Question

Swift - tableview load error - the dreaded SIGBART

Started a Xcode project from scratch. Selected single view option. Dropped in a tableview over the view. Selected 1 cell prototype. Created a cell identifier "cell." Added UITableViewDelegate and functions needed to satisfy tableview protocol. The tableview is linked to the view controller. The code has no pre-run errors or warnings. However, I get this error:

2016-10-15 07:50:29.622 LawDataNHC[5219:196567] * Assertion failure in -[UITableView _configureCellForDisplay:forIndexPath:], /BuildRoot/Library/Caches/com.apple.xbs/Sources/UIKit_Sim/UIKit-3599.6/UITableView.m:8035
2016-10-15 07:50:29.650 LawDataNHC[5219:196567] *
Terminating app due to uncaught exception 'NSInternalInconsistencyException', reason: 'UITableView (; layer = ; contentOffset: {0, 0}; contentSize: {375, 44}>) failed to obtain a cell from its dataSource ()'
*** First throw call stack:

The material tableview code:

class ViewController: UIViewController, UITableViewDelegate {

override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
}

func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {

return 1
}

func numberOfSections(in tableView: UITableView) -> Int {

return 1
}

private func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {

let cell = UITableViewCell(style: .default, reuseIdentifier: "cell")

cell.textLabel?.text = "test"

return cell
}

Answer

You've forgotten to name the protocol UITableViewDataSource in your ViewController

class ViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {

Also your cellForRowAt method shouldn't be private:

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {

And finally try use the dequeueReusableCell method for generating cells instead of creating new ones with UITableViewCell(style: .default, reuseIdentifier: "cell").

Your ViewController class should look like the following:

class ViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {
  func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    return 1
  }

  func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
  //let cell = UITableViewCell(style: .default, reuseIdentifier: "cell")
    let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath)

    cell.textLabel?.text = "test"

    return cell
  }
}
Comments