10
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?

matt
  • 515,959
  • 87
  • 875
  • 1,141
Chris
  • 159
  • 1
  • 8

2 Answers2

19

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
   }
}
Shades
  • 5,568
  • 7
  • 30
  • 48
  • 1
    Thanks @Shades I just had to delete my segue from the cell and drag one from the storyboard! – Chris Sep 05 '16 at 17:54
  • Exactly, and when drag from storyboard it worked for me too even if I still have performSegue on `didSelectRowAtIndexPath() ` method :) tested on Xcode 11.3.1 – Sebastian Jul 09 '20 at 21:36
14

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.

matt
  • 515,959
  • 87
  • 875
  • 1,141