User User - 1 year ago 60
iOS Question

How to pass data when the back button clicked?

I'm trying to pass data from

to another
, I succeed to pass data when I press on
but I couldn't pass data back when I press on back button of navigation bar; I've tried global variables to solve this problem but since I'm storing date of those variables in database it causes a lot of problems to me, because it enforces all stored reminders to save the same data, I could to do some tricks to solve this problem but we all know that global variable is bad practice and does't confirm to
, the question is how to pass data back with using
Prepare for segue
function; note that the table view are static not dynamic.

and if your were asking what data I'm trying to pass is days of week, when Friday and Saturday are selected for example it sends back true values to previous view and if Friday and Saturday are deselected false values are sent back to previous view

so how can I solve this problem?

thanks in advance

Answer Source

You need to do four things:


You should have a custom protocol such as:

public protocol DataBackDelegate: class {
    func savePreferences (preferencesRestaurantsArray : [Bool], preferencesCusinesArray : [Bool])

as you see, I supposed that you want to send back two arrays, but you can edit that in order to send whatever data and datatypes you want.


Your first view controller (or table view controller since table view controller is just a subclass of view controller) has to conform to your custom protocol, such as:

class MainTableViewController: UITableViewController, DataBackDelegate  


In your second view controller, you need to have a variable for that protocol, such as:

 weak var delegate: DataBackDelegate?

and then you catch the back action and inside it you call your custom protocol function, such as:

self.delegate?.savePreferences(Preferences2ViewController.preferencesRestaurantsArray, preferencesCusinesArray: Preferences2ViewController.preferencesCusinesArray)


In your first main controller, in the segue that fires the second view controller, you should set the deleage to self, such as:

destination.dataBackDelegate = self

where destination is the second view controller