为什么默认构造函数和自定义构造函数是为UINavigaionController的子类调用的?
@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的子类调用的?
这是因为你没有正确地实现你的初始化。
在目标C中,有一个概念指定的初始化程序,您的类的一个单一init
函数,所有其他初始化程序必须调用。它是直接调用[super init]
的指定初始化程序;所有其他初始化程序都需要通过调用指定的初始化程序来间接调用[super init]
。
你的具体情况,你需要共同的代码移动到init
和initWithRootViewController:
两个,如果有的话,到initWithRootViewController:
初始化,并重写平原init
如下:
-(id)init {
return [self initWithRootViewController:nil];
}
**编辑:* *(作为对该解决方案引起无限递归的评论的回应),我认为你无限递归的原因必须特别针对UINavigationController
的实现细节,该细节不应该被继承。根据Apple的文档,
UINavigationController
类实现了管理分层内容导航的专用视图控制器。这个类不适用于子类。相反,如果您希望应用程序的用户界面能够反映内容的层次性,您就可以使用它的实例。
编辑:针对子类的禁令已在iOS 6中被揭开 - 看到UINavigationController的文档。
'@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
@Allamaprabhu你是继承'UINavigationController'吗? – dasblinkenlight 2012-08-13 13:05:32
是的,我正在继承。 – Allamaprabhu 2012-08-13 13:13:09
我猜initWithRootViewController:
实现这样的:
-(id)initWithRootViewController:(UIViewController *)rootViewController
{
self=[self init];
if(self)
{
// do something with rootViewController
}
return self;
}
不。我很确定,我不打电话 self = [super init]; 而是我打电话给 self = [super initWithRootViewController:rootViewController]; – Allamaprabhu 2012-08-13 12:26:27
我的答案在哪里,我说你叫'[super init]'? **超类**的'initWithRootViewController'实现调用'[self init]' – 2012-08-13 14:13:36
:对不对!!!!! – Allamaprabhu 2012-08-13 14:21:09
如果您的问题得到解答,请接受其中一个答案。 – 2012-08-16 08:47:11