有三个类,Question,Choice,blank,其中Question是其他两个类的父类。
在Qestion中定义下面的方法:
- (instancetype)initWithQuestionType:(NSString *)questionType
{
NSLog(@"**class:%@",[self class]);
if([self isMemberOfClass:[Question class]])
{
self = nil;
if([questionType isEqualToString:@"choice"])
{
NSLog(@"--class:%@",[self class]);
self = [[Choice alloc] initWithQuestionType:questionType];
NSLog(@"++class:%@",[self class]);
}
else
{
self = [[Blank alloc] initWithQuestionType:questionType];
}
return self;
}
return [super init];
}
- (instancetype)init
{
NSLog(@"Init!");
return [self initWithQuestionType:@"unknow"];
}
执行
Question *question = [[Question alloc] initWithQuestionType:@"choice"];
输出是:
2015-10-16 20:58:50.278 initSample[3687:161396] **class:Question
2015-10-16 20:58:50.279 initSample[3687:161396] --class:(null)
2015-10-16 20:58:50.279 initSample[3687:161396] **class:Choice
2015-10-16 20:58:50.280 initSample[3687:161396] ++class:Choice
我不明白的是为什么[super init]
这条语句没有执行(没有输出Init!
)?
因为
[super init]
调用的是父类的init方法,也就是说在你的[[Question alloc] initWithQuestionType:@"choice"]
调用里面,它所调用的init方法不是你在下面实现的init方法,而是Question的父类的init方法。