Difference between perform segue with identifier and prepare for segue

Uzair picture Uzair · Aug 7, 2015 · Viewed 7.6k times · Source

I am very confuse between "perform segue with identifier" and "prepare for segue"...what these functions do and how they work?

Answer

Dharmesh Kheni picture Dharmesh Kheni · Aug 7, 2015

prepareForSegue prepares data to passed between view controllers where as performSegue with identifier actually allows the switch to happen.

From Apple Documentation:

  • Swift2: performSegueWithIdentifier(_:sender:)
  • Swift3: performSegue(withIdentifier: String, sender: Any?)

    Apps typically do not need to trigger segues programmatically. If needed, you can call this method to trigger a segue for an action that cannot be expressed in a storyboard file, such as a transition between scenes in different storyboards.

    Typically, a segue is triggered by a user action, such as clicking a button. In Interface Builder, configure an object, such as a control embedded in the view controller’s view hierarchy, to trigger the segue.

  • Swift2: prepareForSegue(_:sender:)

  • Swift3: prepare(for: NSStoryboardSegue, sender: Any?)

    The default implementation of this method does nothing; you can override it to pass relevant data to the new view controller or window controller, based on the context of the segue. The segue object describes the transition and includes references to both controllers involved in the segue.

    Segues can be triggered from multiple sources, so use the information in the segue and sender parameters to disambiguate between different logical paths in your app. For example, if the segue originated from a table view, the sender parameter would identify the cell that the user clicked. You could use that information to set the data on the destination view controller.