[self class]和[super class]

2021-03-30  本文已影响0人  磊Se

问题

Teacher继承PersonPerson继承NSObjectsuperself调用class方法打印结果

@implementation Teacher
- (instancetype)init
{
    self = [super init];
    if (self) {
        //猜测 Teacher
        NSLog(@"[self class]:%@",[self class]);
        //猜测 Person
        NSLog(@"[self superclass]:%@",[self superclass]);
        //猜测 Person
        NSLog(@"[super class]:%@",[super class]);
        //猜测 NSObject
        NSLog(@"[super superclass]:%@",[super superclass]);

    }
    return self;
}

实际打印结果

2021-03-30 13:51:23.283653+0800 InterViewTest[6675:102791] [self class]:Teacher
2021-03-30 13:51:23.283698+0800 InterViewTest[6675:102791] [self superclass]:Person
2021-03-30 13:51:23.283736+0800 InterViewTest[6675:102791] [super class]:Teacher
2021-03-30 13:51:23.283773+0800 InterViewTest[6675:102791] [super superclass]:Person

[super class]猜测与我们相差甚远,下面进行分析

[self class]

[self class]实际是调用objc_msgSend()

objc_msgSend(id _Nullable self, SEL _Nonnull op, ...)

self消息接收者SEL则是class方法的选择器

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

/***********************************************************************
* object_getClass.
* Locking: None. If you add locking, tell gdb (rdar://7516456).
**********************************************************************/
Class object_getClass(id obj)
{
    if (obj) return obj->getIsa();
    else return Nil;
}

class方法则返回selfisa,则[self class]原理就解释清楚了

[super class]

[super class]实际是调用objc_msgSendSuper()

objc_msgSendSuper(struct objc_super * _Nonnull super, SEL _Nonnull op, ...)

super是一个关键字,它的本质是objc_super结构体

struct objc_super {
    /// Specifies an instance of a class.
    __unsafe_unretained _Nonnull id receiver;// 消息接收者

    /// Specifies the particular superclass of the instance to message. 
#if !defined(__cplusplus)  &&  !__OBJC2__
    /* For compatibility with old objc-runtime.h header */
    __unsafe_unretained _Nonnull Class class;
#else
    __unsafe_unretained _Nonnull Class super_class;
#endif
     // super_class 是第一个要搜索的类
    /* super_class is the first class to search */ 
};

总结:

上一篇下一篇

猜你喜欢

热点阅读