I'm having some troubles adding new cells on table view.
The strange thing is that I run once the function works perfectly without problems, if I do it for a second time it crash with this error.
* Terminating app due to uncaught exception 'NSRangeException', reason: '* -[__NSSingleObjectArrayI objectAtIndex:]: index 1 beyond bounds [0 .. 0]'
Here my code:
override func viewWillAppear(_ animated: Bool) {
if prodottoDaAggiungere != nil {
prodotti.append(prodottoDaAggiungere!)
let indexPath = IndexPath(row: prodotti.count-1, section: 1)
tableView.insertRows(at: [indexPath], with: .fade) // ?
prodottoDaAggiungere = nil
}
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
if indexPath.row < prodotti.count && indexPath.section == 1 {
let cell = tableView.dequeueReusableCell(withIdentifier: "ProdottoTableViewCell", for: indexPath) as! ProdottoTableViewCell // Crash :|
let indexRow = indexPath.row // Fix
cell.title.text = "\(prodotti[indexRow].prodotto.nome!) - \(prodotti[indexRow].prodotto.marca!)"
cell.subtitle.text = "\(prodotti[indexRow].prodotto.formati[prodotti[indexRow].formato].dimensione) \(prodotti[indexRow].prodotto.unitàMisura!) - \(prodotti[indexRow].prodotto.formati[prodotti[indexRow].formato].prezzo) €"
cell.number.text = Int(cell.stepper.value).description // 1
cell.stepper.addTarget(self, action: #selector(stepperChanged), for: .valueChanged)
return cell
}
return super.tableView(tableView, cellForRowAt: indexPath)
}
Using breakpoint I founded app crash on the dequeueReusableCell but I cannot understand why, someone could tell me why this code crash?
Here my tableView numberOfRowsInSection func:
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
// #warning Incomplete implementation, return the number of rows
if section == 0 {
return 1
} else if section == 1 {
return 1+prodotti.count
} else {
return 0
}
}
Really thanks AP