2

This is a simple question:

I have 2 different view controllers, and each one has its own data stored in its .m file. I want to take a value, for instance, an integer value (int i=3;) that is declared in ViewController1 and pass it to ViewController2, so I will be able to use that value in the second view controller.

Can anyone please tell me how to do it?

Akhil Jain
  • 13,872
  • 15
  • 57
  • 93
Sagiftw
  • 1,658
  • 4
  • 21
  • 25

3 Answers3

2

2014 Edit - in case somebody happens upon this, don't listen to me. The "better way" really is the best way.

Good Way - Create your own initWithI method on ViewController2

Better Way - Create ViewController2 as usual, and then set the value as a property.

Best Way - This is a code smell, you are tightly coupling the data with a ViewController. Use CoreData or NSUserDefaults instead.

bpapa
  • 21,409
  • 25
  • 99
  • 147
1

If you are embedding ViewController1 in an UINavigationController, this is a pretty common use-case. Inside ViewController1, add this code where you want to show the ViewController2 (in an action for example):

ViewController2 *controller = [[ViewController2 alloc] initWithNibName:<nibName> bundle:nil];
[controller setData:<your shared data>]; 
[self.navigationController pushViewController:controller animated:YES];
[controller release];

The navigation controller will take care of the rest.

Laurent Etiemble
  • 27,111
  • 5
  • 56
  • 81
1

Initialize the new view controller with the value.

- (id)initWithValue:(int)someValue {
    if (self = [super initWithNibName:@"MyViewController" bundle:nil]) {
        myValue = someValue;
    }
    return self;
}

Then from your other view controller (assuming this other view controller is owned by a UINavigationController)

- (void)showNextViewControler {
    MyViewController *vc = [[[MyViewController alloc] initWithValue:someValue] autorelease]
    [self.navigationController pushViewController:vc animated:YES];
}

And/or to do it after initialization, create a method or property that allows you to set it.

- (void)setSomeValue:(int)newValue {
    myValue = newValue;
}

Then

- (void)showNextViewControler {
    MyViewController *vc = [[[MyViewController alloc] initWithNibName:@"Foo" bundle:nil] autorelease]
    [vc setValue:someValue]
    [self.navigationController pushViewController:vc animated:YES];
}
Alex Wayne
  • 178,991
  • 47
  • 309
  • 337