s_khillon s_khillon - 2 months ago 12
iOS Question

indexPath.row is out of range (always 0)

I know this question has been asked multiple times already, but for some reason none of the responses I've read has solved this issue. I'm retrieving an array of MealObjects, a class that I have defined, and setting their properties to labels in a Table View with a defined limit of 5 Table View Cells. I only have one section in the Table View.

I've pasted my View Controller class below. I've marked the error in a comment. What am I doing wrong?

import UIKit

class PlateViewController: UITableViewController, UITableViewDataSource, UITableViewDelegate {

@IBOutlet weak var titleLabel: UILabel!
@IBOutlet weak var subtitleLabel: UILabel!

let locationHelper = LocationHelper.sharedInstance
let userChoice = UserChoiceCollectionDataSource()
var mealArray: [MealObject] = []

override func viewDidLoad() {
super.viewDidLoad()
locationHelper.setupLocation()

locationHelper.callback = {
self.mealArray = self.userChoice.getUserSuggestions()
}

tableView.dataSource = self
tableView.delegate = self
tableView.estimatedRowHeight = 125
tableView.rowHeight = UITableViewAutomaticDimension

titleLabel.text = "Your Plate"
subtitleLabel.text = "The top 5 suggestions based on the information you provided"

navigationController?.hidesBarsOnSwipe = true
}

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


let meals = mealArray[indexPath.row]

/* FATAL ERROR: ARRAY INDEX OUT OF RANGE
INDEXPATH.ROW = 0
*/

print(indexPath.row)
cell.mealTitleLabel.text = meals.mealTitle
cell.descriptionLabel.text = meals.mealDescription
cell.priceLabel.text = "\(meals.priceValue)"

return cell
}

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

override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return 5
}

}

Answer

If index 0 is out of range, it looks like your array is empty at the time the cellForRowAtIndexPath accesses it. You hard coded the number of rows to 5, but you should only do that if the array has at least 5 elements in it. For example, in the numberOfRowsInSection you can do

 return min(mealArray.count, 5)

I don't see where you are setting the array. Your code

locationHelper.callback = {

    self.mealArray = self.userChoice.getUserSuggestions()

}

does not do that.

Comments