james james - 4 months ago 9
iOS Question

fatal error: index out of range tableview with two sections

I'm trying to populate a tableView with 2 sections using two arrays of Firebase objects (called snapshots). I'm getting an error in my cellForRowAtIndexPath function when I try to load the tableView:

fatal error: Index out of range
.

override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("PersonCell", forIndexPath: indexPath) as! PersonCell

//set cell text
let guardianDict = guardians[indexPath.row].value as! [String : AnyObject] // error happens here
let dependentDict = dependents[indexPath.row].value as! [String : AnyObject]

cell.personName.text = "test"

return cell
}


Here is how I define my sections:

override func tableView(tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
switch(section){
case 0: return "Dependents"

case 1: return "Guardians"

default: return ""
}
}


Any ideas?
Thanks!

EDIT: Adding the numberOfSections and numberOfRowsInSection:

override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
// #warning Incomplete implementation, return the number of sections
return 2
}

override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
// #warning Incomplete implementation, return the number of rows
switch(section){
case 0: return self.dependents.count

case 1: return self.guardians.count

default: return 1
}
}

Answer

You have two sections in your table with each section coming from different sources. You need to add checking in your cellForRowIndexPath function to access the right array:

override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
  let cell = tableView.dequeueReusableCellWithIdentifier("PersonCell",    forIndexPath: indexPath) as! PersonCell

  if indexPath.section == 0
  {
    let dependentDict = dependents[indexPath.row].value as! [String : AnyObject]
  }
  else if indexPath.section == 1
  {
    let guardianDict = guardians[indexPath.row].value as! [String :  AnyObject] // error happens here
  }
  cell.personName.text = "test"

  return cell
}