问题描述
- Objective-C 关于super的问题
-
有三个类,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
为什么没有输出init方法中的Init!这句话?
解决方案
self = [super init]
解决方案二:
objective-c中的Super
objective-c super
时间: 2024-10-29 06:23:57