How to access the parent view controller?
I am using this code to push a view controller in ViewControllerA
:
DatePickerViewController *viewController = [[DatePickerViewController alloc] initWithNibName:@"DateP开发者_如何学运维ickerViewController" bundle:nil];
NSMutableArray *info = [[NSMutableArray alloc] initWithObjects:@"Exam Duration",nil];
[viewController setInfo:info];
[info release];
[self.navigationController pushViewController:viewController animated:YES];
[viewController release];
In the DatePickerViewController
that is slid in, it has a text field. In ViewControllerA
how can I get the value of this text field once the viewWillDisappear
method is fired, it's to save data.
There are several ways to do this. Best would be to use a delegate pattern or a notification system.
Which one you choose depends on your whishes. If you just want the 'parent controller' to know about the value, use a delegate method.
Using delegates or notifications creates a loosely coupled structure and makes reusable classes possible.
EDIT: Some sample code. Beware: untested and from the top of my head!
DatePickerViewController.h
@protocol DatePickerViewControllerDelegate
-(void)datePicker:(DatePickerViewController *)picker pickedDate:(NSDate *)date;
@end
DatePickerViewController.m
- (void)viewWillDisappear:(BOOL)animated {
[self.delegate datePicker:self pickedDate:theDate]; //Delegate is an ivar
[super viewWillDisappear:animated];
}
ViewControllerA.m
//
DatePickerViewController *viewController = [[DatePickerViewController alloc] initWithNibName:@"DatePickerViewController" bundle:nil];
NSMutableArray *info = [[NSMutableArray alloc] initWithObjects:@"Exam Duration",nil];
[viewController setInfo:info];
[info release];
[viewController setDelegate:self]; // Set the delegate of the date picker
[self.navigationController pushViewController:viewController animated:YES];
[viewController release];
//
-(void)datePicker:(DatePickerViewController *)picker pickedDate:(NSDate *)date; {
//Deal with the new date here
}
精彩评论