Giulio Crisanti
Giulio Crisanti

Reputation: 380

prepareforsegue() not executing (swift/storyboards)

I am making a small test application and am using the "master detail" application template in Xcode. I would like to be able to send an array from the detail view to the master view.

I tried using prepareForSegue() but the problem is that this is never called. When I hit the back button (already there by default (pre generated by Xcode)), it simply doesn't execute the code.

prepareForSegue() however works fine from the master to the detail view.

Sorry if the answer to this question is a obvious, but I am very much new to programming so this has left me a bit perplexed!

Thanks!

Upvotes: 1

Views: 371

Answers (3)

Akash Raghani
Akash Raghani

Reputation: 557

Hope this is helps you...

override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {

    let cell = sender as UITableViewCell
    if segue.identifier == "xyz" {
        var tabBarVC: UITabBarController = segue.destinationViewController as UITabBarController
        var test: LessonsDetailsViewController = tabBarVC.viewControllers?.first as LessonsDetailsViewController
        var row = self.tableView.indexPathForCell(cell)?.row
        var dataObj = lessonsNSMObj[row!]
        test.managedObject = dataObj
    }
}

Upvotes: 0

Ajay Singh Beniwal
Ajay Singh Beniwal

Reputation: 19037

When you go back you are poping navigation stack and prepareForSegue will not be called when you move back from detail to master view. To pass data back from detail to master you will require Unwind Segue. An unwind segue moves backward through one or more segues to return the user to an existing instance of a view controller. You use unwind segues to implement reverse navigation.More detail could be learnt from here https://developer.apple.com/library/prerelease/ios/referencelibrary/GettingStarted/DevelopiOSAppsSwift/Lesson8.html

Upvotes: 2

rickster
rickster

Reputation: 126127

Going "back" through a navigation stack isn't a segue, so it doesn't fire prepareForSegue or other segue-related methods. Usually, navigation stacks are designed such that a master list doesn't need knowledge of what goes on in a detail view, anyway.

If need to, though, you can use the viewWillAppear/viewWillDisappear methods to find out when the user is navigating back from the detail to the master. For example, if all you need to do is make the master list update to reflect changes to a detail item, you can have the master's viewWillAppear implementation call reloadRowsAtIndexPaths:withRowAnimation: with the selected index path (which is still selected from when the user navigated to the detail view). Then your usual logic for populating cells can pick up whatever changes have been made to the object represented by that row (and by the detail view you're returning from).

Upvotes: 2

Related Questions