2011-04-30 31 views
0

我有兩個控制器,First- and SecondViewController。我想分享一些FirstViewController的方法在我的SecondViewController中使用它們。初始化UIViewController時如何傳遞一個參數?

這是我如何FirstViewController創建SecondViewController:

sms = [[SecondViewController alloc] init]; 
UINavigationController *navController = [[UINavigationController alloc] 
              initWithRootViewController:sms]; 

[self presentModalViewController:navController animated:YES]; 

我以爲經過FirstViewController當前實例延伸UIViewController的SecondViewController的。默認情況下,調用SecondViewController的initWithNibName方法。

如何在objective-c中實現這一點?

+0

你問如何將FirstViewController傳入init方法中的SecondViewController而不使用initWithNibName初始值設定項? – 2011-04-30 15:15:37

+0

我不會調用initWithNibName mehtod,它似乎被自動調用,但是我很欣賞任何有關如何將第一個傳遞給第二個視圖控制器的建議 – 2011-04-30 15:28:52

回答

3

我不完全確定我明白這個問題...作爲問題的一部分與如何實例化SecondViewController有關......發佈代碼可能有所幫助。

但在你的SecondViewController.h回答你的問題,你問它....「怎麼FirstViewController進入SecondViewController」 ......

創建自己的init方法

-(id) initWithFirstViewController:(UIViewController *)theFirstViewController; 

而在.m文件...

-(id) initWithFirstViewController:(UIViewController *)theFirstViewController 
{ 
    self = [super initWithNibName:@"myNibName" bundle:nil]; 

self.firstViewController = theFirstViewController; //this assumes you have created this property. Also, do NOT retain the first view controller or you will get circular reference and will secondviewcontroller will leak. 



return self; 

} 

然後..這裏是關鍵..請確保您調用正確的init()方法來實例化SecondViewContoller

SecondViewController *svc = [[SecondViewController alloc]initWithFirstViewController:self]; 

現在..話說..看你的SO等級,我中有你已經知道這一點的感覺..和真正的問題可...爲什麼是initWithNibName被當你不叫實際上明確地調用它?

1

不是100%確定你在做什麼。有關共享方法的問題的內容似乎與在init中傳入參數的問題不匹配。

至於方法,你可以從你的parentViewController調用一個方法

if ([self.parentViewController respondsToSelector:@selector(someMethod)]) { 
    [self.parentViewController someMethod]; 
} 

如果你想在init在任何類傳遞參數,你將要編寫自定義init方法與任何附加你想要的參數。該自定義方法應該從適當的[self init]調用開始。你甚至可以有多個自定義的方法,可以很方便。

下面是下載json或xml提要的類的示例。

- (id)initWithID:(NSString *)useID delegate:(id)setDelegate urlString:(NSString *)urlString feedIsJSON:(BOOL)feedIsJSON failedRetrySecondsOrNegative:(float)failedRetrySecondsOrNegative refreshSecondsOrNegative:(float)refreshSecondsOrNegative { 

    if ((self = [super init])) { 
     // Custom initialization   
     processing = NO; 
     self.delegate = setDelegate; 

     self.feedID = [NSString stringWithFormat:@"%@", useID]; 
     self.feedURLString = [NSString stringWithFormat:@"%@", urlString]; 
     self.isJSON = feedIsJSON; 

     if (failedRetrySecondsOrNegative>=0.0f) { 
      retryFailedSeconds = failedRetrySecondsOrNegative; 
     } else { 
      retryFailedSeconds = kFailedRefresh; 
     } 

     if (refreshSecondsOrNegative>=0.0f) { 
      refreshSeconds = refreshSecondsOrNegative; 
     } else { 
      refreshSeconds = kSuccededRefresh; 
     } 

    } 
    return self; 
} 

希望這會有所幫助。

相關問題