2015-09-20 119 views
1

我有一些重複的代碼我試圖重構:視圖控制器的動態類型

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-在頂部!)

回答

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]; 
+0

其中之一(ConfirmationViewController)是一個tableViewController - 是否有可能讓這個共享基類? – thisAnneM

+0

@thisAnneM你可以使用一個通用的協議,看看編輯。 – dasblinkenlight

1

如果你可以保證他們都有一個patient,他們都有questions那麼你可以讓他們都從一個單一的UIViewController子類繼承,有這些東西,或使他們都採用需要這些事情的協議。就個人而言,我會去的UIViewController子類。