2012-08-17 28 views
0

比方說,我有這樣的代碼:使用多個類文件代碼

if ([resultButton.titleLabel.text isEqualToString:@"Tax"]) { 

     TAXViewController *controller = [[TAXViewController alloc]initWithNibName:@"TAXViewController" bundle:nil]; 
     controller.modalTransitionStyle = UIModalTransitionStyleCrossDissolve; 
     [self presentViewController:controller animated:YES completion:nil]; 
     [controller release]; 

    }else if ([resultButton.titleLabel.text isEqualToString:@""]){ 

     RENTViewController *controller = [[RENTViewController alloc]initWithNibName:@"RENTViewController" bundle:nil]; 
     controller.modalTransitionStyle = UIModalTransitionStyleCrossDissolve; 
     [self presentViewController:controller animated:YES completion:nil]; 
     [controller release]; 

    }else if //repeats a lot...... 

而且我想使用多個.h文件此完全相同的代碼。有沒有辦法編寫代碼(只在一個地方),並從其他.h文件訪問它,而不必在任何地方重複?

因此,最後我猜,我可以傳遞一個字符串到其他.h/.m文件,它會打開匹配字符串的視圖。

+1

把它放在一個函數? – 2012-08-17 18:16:35

+0

是的,但我想從多個類(.h .m?) – 2012-08-17 18:39:46

+0

,而不是'[self openNewView:@「View」]訪問它;'有它來電另一個.h – 2012-08-17 18:40:44

回答

1

把它放在一個類中,並使你想要在其子類中訪問它的所有其他文件。

@interface SomeController : BaseViewController 

您也可以WAY簡化代碼

UIViewController *controller; 
if ([resultButton.titleLabel.text isEqualToString:@"Tax"]) 
     controller = [[TAXViewController alloc]initWithNibName:@"TAXViewController" bundle:nil]; 
else if ([resultButton.titleLabel.text isEqualToString:@""])  
     controller = [[RENTViewController alloc]initWithNibName:@"RENTViewController" bundle:nil]; 
else if 
.... 
//after all if-else statements 
controller.modalTransitionStyle = UIModalTransitionStyleCrossDissolve; 
[self presentViewController:controller animated:YES completion:nil]; 
[controller release]; 
+0

啊,是的,謝謝你的簡化版本。正在尋找。 – 2012-08-17 18:03:58

+0

雖然你並沒有真正理解你提到的第一件事。我添加了我希望它結束​​的內容。 – 2012-08-17 18:05:44

+0

基本上,寫一個視圖控制器(或任何類型的文件,你試圖把它)有這個方法在其中,沒有別的。然後做我放在方法頂部的東西(將':FileName'添加到接口聲明中)。然後它是該視圖控制器的一個子類,所以即使沒有聲明方法,你仍然可以執行'[self callMethod]'。 – Dustin 2012-08-17 18:46:55

相關問題