@interface Person : NSObject
- (void)run;
@end
@implementation Person
- (void)run
{
NSLog(@"%s", __func__);
}
@end
@interface Student : Person
@end
@implementation Student
//重写run方法
- (void)run
{
// super调用的receiver仍然是Student对象
[super run];
//底层实现
// struct objc_super arg = {self, [Person class]};
// objc_msgSendSuper(arg, @selector(run));
}
@end
[super message]的底层实现
1.消息接收者仍然是子类对象
2.从父类开始查找方法的实现
//结构
struct objc_super {
__unsafe_unretained _Nonnull id receiver; // 消息接收者
__unsafe_unretained _Nonnull Class super_class; // 消息接收者的父类
}
无论是[self class]还是[super class]找到的class都是在NSObject里面 只不过[self class]是从当前类对象开始查找 [super class]是从当前类对象的父类开始查找
Student调用init方法
- (instancetype)init
{
if (self = [super init]) {
//objc_msgSend(self, @selector(class));
NSLog(@"[self class] = %@", [self class]); // Student
NSLog(@"[self superclass] = %@", [self superclass]); // Person
NSLog(@"--------------------------------");
// objc_msgSendSuper({self, [Person class]}, @selector(class));
//看起来是[super class],但是方法调用者还是self,
NSLog(@"[super class] = %@", [super class]); // Student
//当前类型是Student 父类是Person
NSLog(@"[super superclass] = %@", [super superclass]); // Person
}
return self;
}
NSObject的实现大概
@implementation NSObject
//返回值取决于self即消息接受者,谁调用就返回谁的类型
- (Class)class
{
return object_getClass(self);
}
//把self传进去 获取当前类型 再告诉当前类型的父类
- (Class)superclass
{
return class_getSuperclass(object_getClass(self));
}
@end