我正在使用此代码在ViewControllerA中推送视图控制器:

DatePickerViewController *viewController = [[DatePickerViewController alloc] initWithNibName:@"DatePickerViewController" bundle:nil];
NSMutableArray *info = [[NSMutableArray alloc] initWithObjects:@"Exam Duration",nil];
[viewController setInfo:info];
[info release];
[self.navigationController pushViewController:viewController animated:YES];
[viewController release];


在滑入的DatePickerViewController中,它具有一个文本字段。在ViewControllerA中,一旦触发viewWillDisappear方法,如何保存此文本字段的值,即保存数据。

最佳答案

有几种方法可以做到这一点。最好是使用委托模式或通知系统。

您选择哪种取决于您的意愿。如果只希望“父控制器”知道该值,请使用委托方法。

使用委托或通知会创建松散耦合的结构,并使可重用的类成为可能。

编辑:一些示例代码。当心:未经测试,从我的头顶上!

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
}

关于ios - 如何访问父 View Controller ?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/2760679/

10-12 01:49