Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Segue is being executed twice

func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
   self.selectedClubState = stateNamesForDisplay[indexPath.row]
   self.performSegueWithIdentifier ("Cities", sender: self)
}

override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
    var clubsToPassToCitiesViewController = [clubObject]()
    if segue.identifier == "Cities" {
        for club in clubsForTable{
            if club.clubState == self.selectedClubState{
                clubsToPassToCitiesViewController.append(club)
            }
        }
       let citiesView = segue.destinationViewController as? citiesViewController
       citiesView?.clubsForChosenCity = clubsToPassToCitiesViewController
   }
}

Segue is being executed twice leading to the next VC. How can I prevent this from happening?

like image 953
Chris Avatar asked Sep 05 '16 17:09

Chris


2 Answers

Delete the current segue in storyboard. Then CTRL-drag from the viewController (not the cell) to the next view controller and name it "Cities". Now, when you select a cell, the didSelectRowAtIndexPath() will fire first and will call performSegueWithIdentifier()

enter image description here

However, if all you're looking to do in the didSelectRowAtIndexPath() is get the row that performed the segue, you can maintain your original setup of having the cell segue from the storyboard, remove didSelectRowAtIndexPath() and in prepareForSegue() do:

override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
    if let indexPath = self.tableView.indexPathForSelectedRow {
        self.selectedClubState = stateNamesForDisplay[indexPath.row]
    }
    var clubsToPassToCitiesViewController = [clubObject]()
    if segue.identifier == "Cities" {
        for club in clubsForTable{
            if club.clubState == self.selectedClubState{
                clubsToPassToCitiesViewController.append(club)
            }
        }
       let citiesView = segue.destinationViewController as? citiesViewController
       citiesView?.clubsForChosenCity = clubsToPassToCitiesViewController
   }
}
like image 161
Shades Avatar answered Oct 01 '22 14:10

Shades


You are the one executing the segue twice — once automatically in the storyboard (because your segue emanates as an Action Segue from the cell prototype), and once in code when you say self.performSegueWithIdentifier. If you don't want the segue executed twice, remove one of those.

Personally, my recommendation is that you delete didSelectRow entirely and move your self.selectedClubState assignment into prepareForSegue.

like image 22
matt Avatar answered Oct 01 '22 14:10

matt