2012-08-13 107 views
2
@implementation NVController 
//Plain Init method 
-(id)init 
{ 

    self=[super init]; 
    if(self) 
    { 
    } 
    return self; 
} 

//CustomInit Method 
-(id)initWithRootViewController:(UIViewController *)rootViewController 
{ 

    self=[super initWithRootViewController:rootViewController]; 
    if(self)`enter code here` 
    { 
    } 
    return self; 
} 

@end 

NVController *instance=[[NVController alloc] initWithRootViewController:nil]; 

這裏在上面的情況下,因爲我只打電話initWithRootViwController,另一個構造函數init也被調用。任何幫助,將不勝感激。爲什麼默認構造函數和自定義構造函數是爲UINavigaionController的子類調用的?

+0

如果您的問題得到解答,請接受其中一個答案。 – 2012-08-16 08:47:11

回答

2

這是因爲你沒有正確地實現你的初始化。

在目標C中,有一個概念指定的初始化程序,您的類的一個單一init函數,所有其他初始化程序必須調用。它是直接調用[super init]的指定初始化程序;所有其他初始化程序都需要通過調用指定的初始化程序來間接調用[super init]

你的具體情況,你需要共同的代碼移動到initinitWithRootViewController:兩個,如果有的話,到initWithRootViewController:初始化,並重寫平原init如下:

-(id)init { 
    return [self initWithRootViewController:nil]; 
} 

**編輯:* *(作爲對該解決方案引起無限遞歸的評論的迴應),我認爲你無限遞歸的原因必須特別針對UINavigationController的實現細節,該細節不應該被繼承。根據Apple的文檔,

UINavigationController類實現了管理分層內容導航的專用視圖控制器。這個類不適用於子類。相反,如果您希望應用程序的用戶界面能夠反映內容的層次性,您就可以使用它的實例。

編輯:針對子類的禁令已在iOS 6中被揭開 - 看到UINavigationController的文檔。

+0

'@implementation NVController // Plain Init method - (id)init { return [self initWithRootViewController:nil]; } // CustomInit方法 - (ID)initWithRootViewController:(UIViewController中*)RootViewController的 { 自我= [超級initWithRootViewController:RootViewController的]; if(self) { } return self; } @end ' 這裏導致無限循環 – Allamaprabhu 2012-08-13 12:46:07

+0

@Allamaprabhu你是繼承'UINavigationController'嗎? – dasblinkenlight 2012-08-13 13:05:32

+0

是的,我正在繼承。 – Allamaprabhu 2012-08-13 13:13:09

2

我猜initWithRootViewController:實現這樣的:

-(id)initWithRootViewController:(UIViewController *)rootViewController 
{ 
    self=[self init]; 
    if(self) 
    { 
     // do something with rootViewController 
    } 
    return self; 
} 
+0

不。我很確定,我不打電話 self = [super init]; 而是我打電話給 self = [super initWithRootViewController:rootViewController]; – Allamaprabhu 2012-08-13 12:26:27

+0

我的答案在哪裏,我說你叫'[super init]'? **超類**的'initWithRootViewController'實現調用'[self init]' – 2012-08-13 14:13:36

+0

:對不對!!!!! – Allamaprabhu 2012-08-13 14:21:09

相關問題