Reputation: 1658
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?
Upvotes: 2
Views: 1792
Reputation: 21497
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.
Upvotes: 2
Reputation: 27889
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.
Upvotes: 1
Reputation: 186984
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];
}
Upvotes: 1