This question already has an answer here:
- Passing Data between View Controllers 42 answers
This is a Q&A Style Post
If I want to pass parameters, such as an NSString
, NSArray
, or NSDictionary
, from one view controller to another, what is the easiest way to do this?
There are multiple ways to achieve this, but two of the cleanest methods would involve passing the parameter(s) into a custom init method for the next view controller, or setting the parameter(s) as a property of the next view controller.
Note that this is not restricted to passing data between view controllers - view controllers are objects and any objects can use the following principles, I'm simply using view controllers for the following examples.
Both of these examples are using a simple UITableViewController as the initial view controller, and the next view controller will be passed the user's selection from a list of cells where they can choose their favorite color, as well as the current date of their selection. This can be done FROM any type of view controller TO any type of view controller with a few minor modifications, and within reason there's really no limit to the types/quantity of information that can be passed this way.
keep in mind that you likely don't want a massive initializer method with 10 parameter names, so in that case you might want to have individual properties and set each one accordingly. You also might want to keep the initialization/setup code to a single line if there's only a few parameters, so using a custom initializer method might be for you in that case.
Demo table view setup
Method #1 - Custom Initializer
NextViewController.h
NextViewController.m
Implement method #1 in our demo table view:
Method #2 - Creating/Setting Properties
NextViewController.h
NextViewController.m
Implement method #2 in our demo table view:
In both instances, you have now quickly and easily passed multiple pieces of information from one view controller to another.