我有一些重复的代码我试图重构:
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...]
和{ {1}},只需在运行特定于案例的代码片段后调用该块,但由于它们都是不同的类型,我无法弄清楚如何声明这个'视图'变量(我主要是JS背景,所以我习惯[setQuestions:_questions]
- 在顶部!)
答案 0 :(得分:2)
让您的三个视图控制器实现一个通用协议:
@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];
答案 1 :(得分:1)
如果你可以保证它们都有一个patient
并且它们都有questions
那么你可以让它们全部从一个具有这些东西的UIViewController子类继承,或者让它们全部采用一个协议需要那些东西。就个人而言,我会选择UIViewController子类。