Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Error with passing data between tableview

I want to pass data from first table view controller to second table view controller. I using this code to do it:

first view controller:

func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
            
        let detailViewController = DetailViewController()
        detailViewController.index = indexPath.row + 1
        print(detailViewController.index) // get correct indexPath.row
            
        navigationItem.backBarButtonItem = UIBarButtonItem(title: "", style: .plain, target: nil, action: nil)
        self.navigationController?.pushViewController(DetailViewController(), animated: true)
    }

second view controller:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

var index = Int()

override func viewDidLoad() {
        super.viewDidLoad()
        print(index) // get nil
}

Why this happens and how to fix it?

>Solution :

You’re creating two instances of DetailViewController, separately.

//This one with a valid index
let detailViewController = DetailViewController()
detailViewController.index = indexPath.row + 1
//This one without an index
self.navigationController?.pushViewController(DetailViewController(), animated: true)

You should pass the first one into .pushViewController like this:

self.navigationController?.pushViewController(detailViewController, animated: true)
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading