Search code examples
iosswiftuitableviewcore-datadidselectrowatindexpath

How to select the correct entity in didSelectRowAt indexPath


My tableview is sorted by the name attribute. So if I enter the names "Hanna" then "Belle" the tableview will look like:


Belle


Hanna


But when I select one cell, the data from the other cell is presented because of the order I entered it I guess. How can I fix this?

MainTableViewController.swift

override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath) as? MainTableViewCell

    let pet = fetchedResultsController.object(at: indexPath)

    cell?.nameLB.text = pet.name
    if pet.isDog {
        cell?.isDogString = "dog"
        cell?.petImage.image = UIImage(named: "dog.png")
    } else {
        cell?.isDogString = "cat"
        cell?.petImage.image = UIImage(named: "cat.png")
    }
    if pet.isBoy {
        cell?.backgroundColor = UIColor(red: 102/255, green: 230/255, blue: 255/255, alpha: 1.0)
    } else {
        cell?.backgroundColor = UIColor(red: 255/255, green: 153/255, blue: 255/255, alpha: 1.0)
    }
    return cell!
}

override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
    let vc = storyboard?.instantiateViewController(withIdentifier: "PetSelectedViewController") as! PetSelectedViewController
    vc.pet = pets[indexPath.row]
    _ = navigationController?.pushViewController(vc, animated: true)
}

PetSelectedViewController.swift

var pet: Pet! // entity

override func viewDidLoad() {
    super.viewDidLoad()
    basicPetInfoUI()
    loadData()
}

func loadData() {
    var isBoyString = ""
    var isVaccString = ""
    pet!.isBoy ? (isBoyString = "Boy") : (isBoyString = "Girl")
    pet!.isVaccinated ? (isVaccString = "Vaccinated") : (isVaccString = "Not Vaccinated")
    nameLabel.text = pet.name
    breedLabel.text = pet.breed
    isBoyLabel.text = isBoyString
    isVaccinatedLabel.text = isVaccString
    weightLabel.text = pet.weight
}

If more information is needed, please let me know and I will edit my question.


Solution

  • Inside cellForRowAt you use fetchedResultsController

    let pet = fetchedResultsController.object(at: indexPath)
    

    But inside didSelectRowAt you use pets

    vc.pet = pets[indexPath.row]
    

    you have to use the same array in both