[self class]和[super class]

@interface DDAnimal : NSObject
@end
@implementation DDAnimal
@end

@interface DDCat : DDAnimal
@end

@implementation DDCat
- (instancetype)init
{
    self = [super init];
    if (self) {
        NSLog(@"self class is : %@", [self class]);
        NSLog(@"super class is : %@", [super class]);
    }
    return self;
}
@end

打印结果:

self class is : DDCat
super class is : DDCat

首先看下NSObject.h 中的 @protocol NSObject 协议

@protocol NSObject
@property (readonly) Class superclass;
- (Class)class;
..../// 其他省略
@end

可以看到 NSObject 实现了 - (Class)class方法

首先我们要知道方法调用顺序:
当前类->父类->...->NSObject(以下self 代表DDCat类)
1、在执行[self class]方法时,会先在DDCat类中查找,DDCat没有实现,然后去DDAnimal类去查找,DDAnimal 类没有实现,然后去NSObject类去查找。
2、在执行[super class]方法时,会先在DDAnimal类中查找,DDAnimal 类没有实现,然后去NSObject类去查找。


此时看下NSObject类源代码内部是怎么实现的:

+ (Class)class {
    return self;
}
- (Class)class {
    return object_getClass(self);
}

可见隐藏参数 self 为 DDAnimal的实例


struct objc_object {
private:
    isa_t isa;

public:

    // ISA() assumes this is NOT a tagged pointer object
    Class ISA();

    // rawISA() assumes this is NOT a tagged pointer object or a non pointer ISA
    Class rawISA();

    // getIsa() allows this to be a tagged pointer object
    Class getIsa();

源码下载地址: https://opensource.apple.com/tarballs/objc4/


你可能感兴趣的:([self class]和[super class])