CJiYI CJiYI - 4 months ago 9
Objective-C Question

Why does the 'init' method run in two times by the same object?

I know the 'init' method of superclass(Person) can be executed before executing the 'init' method of subclass (Student).But why those two or three 'init'(I guess the 'init' of NSObject can be executed as well) can be executed by the same object(s) of Student?

@interface Person : NSObject
@end

@implementation Person
- (id)init{
if (self = [super init]) {
NSLog(@"init--------%@",[self class]);
}
return self;
}
@end

@interface Student : Person
@end

@implementation Student
- (id)init{
if (self = [super init]) {
NSLog(@"init--------%@",[self class]);
}
return self;
}
@end


int main(int argc, const char * argv[]) {

Student *s = [Student alloc];
Student *ss = [s init];

return 0;

}


My code's result:

init--------Student

init--------Student

Avi Avi
Answer

When you call a method of your superclass, your class type hasn't changed. When you init the Student object, it calls the init of Person, but it's still a Student.