7

some days ago I wrote a method to load a view controller using presentViewController:

-(void)passaGC:(NSString *)user
{
UIStoryboard *storyboard = [UIStoryboard storyboardWithName:@"Main" bundle:nil];
UIViewController *viewController = (UIViewController *)[storyboard instantiateViewControllerWithIdentifier:@"generaC"];
[self presentViewController:viewController animated:YES completion:nil];

}

But today I need to pass the variable user from this method to the loaded viewController.

How can I modify my method to do this?

I found other question on stack overflow but nothing is really similar to my request

Gualty
  • 251
  • 1
  • 4
  • 13
  • possible duplicate of [Passing Data between View Controllers](http://stackoverflow.com/questions/5210535/passing-data-between-view-controllers) – user1459524 Mar 09 '14 at 13:33
  • There are actually plenty of questions and answers on SO about this. – user1459524 Mar 09 '14 at 13:33
  • I understand but can someone help me to modify my method? Thanks – Gualty Mar 09 '14 at 13:38
  • You need to do more than modify the method. The answer I linked to (http://stackoverflow.com/questions/5210535/passing-data-between-view-controllers) provides step by step instructions for "passing data forward". – user1459524 Mar 09 '14 at 13:39

2 Answers2

11

add a property to your destination viewController (in the .h):

@property (strong, nonatomic) NSString *user;

and finally your method will look like

-(void)passaGC:(NSString *)user
{
UIStoryboard *storyboard = [UIStoryboard storyboardWithName:@"Main" bundle:nil];
UIViewController *viewController = (UIViewController *)[storyboard instantiateViewControllerWithIdentifier:@"generaC"];

viewController.user = user;

[self presentViewController:viewController animated:YES completion:nil];

}
Armand DOHM
  • 1,121
  • 1
  • 7
  • 9
4

Swift Solution

Except @IBOutlets, you can simply assing data to destination view controller properties.

DestinationVC.swift

var name: String?

SourceVC.swift

let storyboard = UIStoryboard(name: "Helper", bundle: nil)
let destinationVC = storyboard.instantiateViewControllerWithIdentifier("DestinationSID") as! DestinationVC
destinationVC.name = "Mustafa"
presentViewController(destinationVC, animated: true, completion: nil)
muhasturk
  • 2,534
  • 20
  • 16