views:

173

answers:

3

Hi, 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?

Thanks in advance, Sagiftw

+1  A: 

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
A: 

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];
}
Squeegy
A: 

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
NSUserDefaults sounds as the simplest solution.