super 详解

2021-05-09  本文已影响0人  张_何
struct objc_super2{
  id receiver; // 消息接收者
  Class current_class; // receiver 的 Class 对象
}
@interface Person : NSObject
@end
@implementation Person
@end

@interface Student : Person
@end
@implementation Student
- (instancetype)init{
    if (self = [super init]) {
        NSLog(@"[self class] = %@", [self class]); // Student
        NSLog(@"[self superclass] = %@", [self superclass]); // Person
        NSLog(@"[super class] = %@", [super class]); // Student
        NSLog(@"[super superclass] = %@", [super superclass]);// Person
    }
    return self;
}
@end

对于上面[super superclass]显示的是 Person,是这样的 superclass方法的调用者是 super,本质还是 Student 对象,不过要从Student 的父类 Person 中去找superclass方法,但调用者还是 Student 对象,Student 对象调用 superClass 方法返回的自然是 Person.

上一篇 下一篇

猜你喜欢

热点阅读