Search code examples
iosswifttableviewdata-transferdidselectrowatindexpath

When executing DidSelectRowAt, variables no longer have their values


I am currently working on one project, but I have encountered this problem. When executing didSelectRowAt, variables that are not being assigned within initializing are being deleted. Basically, I need to get value of what row did I select previously if I did. I have done this project to simplify the problem. I have two ViewControllers and when I click on any of the rows from tableView at the first ViewController, it switches to the second ViewController. There the value is changing in the original project. When coming back to the first ViewController I need to compare this indexValue with the row I click. Any advice will be appreciated. :)

The First ViewController

var globalIndex: Int!
var delegate: passDataDelegate!
let valueForExample = "This is just to show, how program behaves."

func passData(index: Int?) {
    globalIndex = index
    //When printing globalIndex, it shows normal value
}

let array = ["Row 1", "Row 2", "Row 3", "Row 4"]

func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    return array.count
}

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCell(withIdentifier: "customTableView", for: indexPath) as! CustomTableViewCell
    cell.label.text = array[indexPath.row]
    return cell
}

func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {

    print("Global index is \(globalIndex)")
    //When printing globalIndex, the value is always nil, however when I print valueForExample it normally shows its value
    if(globalIndex == indexPath.row) {
        print("You pressed the same button as before")
    }
    let secondVC = storyboard?.instantiateViewController(withIdentifier: "secondVC") as! SecondViewController
    delegate = secondVC
    delegate.passData(index: indexPath.row)
    secondVC.modalPresentationStyle = .fullScreen
    present(secondVC, animated: true)
}

@IBOutlet weak var tableView: UITableView!

override func viewDidLoad() {
    super.viewDidLoad()
    initialConfiguration()

}

func initialConfiguration() {
    tableView.delegate = self
    tableView.dataSource = self
    tableView.register(UINib(nibName: "CustomTableViewCell", bundle: nil), forCellReuseIdentifier: "customTableView")
}

Second ViewController

protocol delegate {
    func passData(index: Int?)
}
class SecondViewController: UIViewController, passDataDelegate {

    var globalIndex: Int!
    var delegat: delegate!

    override func viewDidLoad() {
        super.viewDidLoad()

    }

    @IBAction func button(_ sender: UIButton) {
        let firstVC = storyboard?.instantiateViewController(withIdentifier: "firstVC") as! ViewController
        delegat = firstVC
        delegat.passData(index: globalIndex)
        dismiss(animated: true, completion: nil)
    }

    func passData(index: Int) {
        globalIndex = index
    }
}

Solution

  • In First ViewController

    var globalIndex: Int? //Make global index optional
    
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
    
        print("Global index is \(globalIndex)")
    
        if(globalIndex == indexPath.row) {
            print("You pressed the same button as before")
        }
    
        let secondVC = storyboard?.instantiateViewController(withIdentifier: "secondVC") as! SecondViewController
        secondVC.delegat = self // Set delegate
        secondVC.globalIndex = indexPath.row //Set global index
        secondVC.modalPresentationStyle = .fullScreen
        present(secondVC, animated: true)
    }
    
    extension FirstViewController: passDelegate {
        func passData(index: Int?){
            globalIndex = index // Set index from second view controller to first viewcontroller
        }
    }
    

    In Second ViewController

    protocol passDelegate {
        func passData(index: Int?)
    }
    
    class SecondViewController: UIViewController {
       var globalIndex: Int!
       var delegat: delegate!
    
       override func viewDidLoad() {
          super.viewDidLoad()
       }
    
       @IBAction func button(_ sender: UIButton) {
           delegat.passData(index: globalIndex) //Call delegate
           dismiss(animated: true, completion: nil)
       }
     }