视图控制器的动态类型
问题描述:
我有一些重复的代码我试图重构:视图控制器的动态类型
if (_currentIndex >= [_questions count] - 1) {
[patient setDate:[NSDate date]];
ConfirmationViewController *confirmation = [self.storyboard instantiateViewControllerWithIdentifier:@"Confirmation"];
[confirmation setPatient:patient];
[confirmation setQuestions: _questions];
[self.navigationController pushViewController:confirmation animated:YES];
} else if ([[_questions objectAtIndex:_currentIndex + 1] isEqualToString:@"date"]) {
DateViewController *dateView = [self.storyboard instantiateViewControllerWithIdentifier:@"Date"];
[dateView setPatient:patient];
[dateView setQuestions: _questions];
[dateView setCurrentIndex: _currentIndex + 1];
[self.navigationController pushViewController:dateView animated:YES];
} else {
QuestionViewController *nextQuestion = [self.storyboard instantiateViewControllerWithIdentifier:@"Question"];
[nextQuestion setCurrentIndex:_currentIndex + 1];
[nextQuestion setPatient:patient];
[nextQuestion setQuestions: _questions];
[self.navigationController pushViewController:nextQuestion animated:YES];
}
我想声明一个变量nextView
这可以是一个ConfirmationViewController,DateViewController,或QuestionViewController,因为所有其中的步骤有setPatient:patient
,[self.navigationController pushViewController...]
和[setQuestions:_questions]
,并且在运行特定于代码段的代码之后调用该块,但由于它们都是不同的类型,我无法弄清楚如何声明这个'view'变量(我主要是JS背景,所以我已经习惯了var
-在顶部!)
答
有你的三个视图控制器实现一个共同的协议:
@protocol BaseViewController
@property (readwrite, copy) MyPatient *patient;
@property (readwrite, copy) NSArray *questions;
@end;
@interface ConfirmationViewController : UITableViewController <BaseViewController>
...
@end
@interface DateViewController : UIViewController <BaseViewController>
...
@end
@interface QuestionViewController : UIViewController <BaseViewController>
...
@end
现在您可以BaseViewController
类型的变量,并设置条件外的公共属性:
UIViewController<BaseViewController> *vc;
if (_currentIndex >= [_questions count] - 1) {
[patient setDate:[NSDate date]];
vc = [self.storyboard instantiateViewControllerWithIdentifier:@"Confirmation"];
} else if ([[_questions objectAtIndex:_currentIndex + 1] isEqualToString:@"date"]) {
vc = [self.storyboard instantiateViewControllerWithIdentifier:@"Date"];
[vc setCurrentIndex: _currentIndex + 1];
} else {
vc = [self.storyboard instantiateViewControllerWithIdentifier:@"Question"];
[vc setCurrentIndex:_currentIndex + 1];
}
[vc setPatient:patient];
[vc setQuestions: _questions];
[self.navigationController pushViewController:vc animated:YES];
答
如果你可以保证他们都有一个patient
,他们都有questions
那么你可以让他们都从一个单一的UIViewController子类继承,有这些东西,或使他们都采用需要这些事情的协议。就个人而言,我会去的UIViewController子类。
其中之一(ConfirmationViewController)是一个tableViewController - 是否有可能让这个共享基类? – thisAnneM
@thisAnneM你可以使用一个通用的协议,看看编辑。 – dasblinkenlight