Previously, I’ve been in the position where I need to send a variable to a modal view controller that I’m about to present.
Here is my presenting code in my MainViewController:
|
1 2 |
modalViewController = [[ModalViewController alloc] initWithNibName:@"ModalViewController" bundle:nil]; [self presentModalViewController:modalViewController animated:YES]; |
So I want to send the variable ‘variableName’ to my modal view controller.
In order to do this, I first need to allow my modalViewController access a variable called variableName and make it available.
First, create a property in ModalViewController.h
|
1 |
@property (nonatomic, retain) id variableName; |
Now synthesize it with a unique accessor name (denoted by an underscore)
|
1 |
@synthesize variableName=_variableName; |
Lastly, in my MainViewController.h, I need to give it access to all properties of the ModalViewController by adding the class reference.
|
1 |
@class ModalViewController; |
Now everything is linked up to where it should be, you can now explicitly set the variable.
Back in the presenting modal view controller code:
|
1 2 3 |
modalViewController = [[ModalViewController alloc] initWithNibName:@"ModalViewController" bundle:nil]; [self presentModalViewController:modalViewController animated:YES]; modalViewController.variableName = @"Test String"; |
Extra Credit
You can also do some additional processing in the ModalViewController upon setting the variableName variable. This will allow us to execute any additional commands on the variableName at the point it was set.
In the ModalViewController.m
|
1 2 3 4 5 6 7 |
- (void)setVariableName:(id)newVariableName { if (_variableName != newVariableName) { [_variableName release]; _variableName = [newVariableName retain]; } } |
By creating a setter, I can process the variableName however I would like.
In my particular example, I collected the selected field of a UITableView’s text label and stored it in the modalViewController’s variableName, then I was able to use the variableName to query a database and return a particular set of results. I processed the query at the time the variable was set, before any other methods had executed.
Comments
Powered by Facebook Comments