有一道面试题:son
继承自person
,在son
的方法中有id retval1 = [self class]
和id retval2 = [super class]
,问retval1
和retval2
分别为什么?
我们知道打印的都是son,那么runtime是如何实现这两个的呢?
由id retval1 = [self class]
我们知道应该是这样:
id retval1 = objc_msgSend(self,sel_registerName("class"));
而id retval2 = [super class]
的实现是这样的:
struct objc_super objcSuper = {self,class_getSuperclass(objc_getClass("son"))};
id retval2 = objc_msgSendSuper2(&objcSuper,sel_registerName("class"));
其实可以看到,两处的self
都是指son
。
我们通过OC语法看class
方法注释:
90B55446-C3AB-4A26-931C-7DDF99DE6F27.png
可以看到返回值是
receiver's class
,即消息接受者的类。
再看看对objc_msgSend
函数和objc_super
结构体中使用的self
的注释均为receiver
,那么就不难理解为什么打印出来的都是son
了。
附上objc_super
的结构:
/// Specifies the superclass of an instance.
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 is the first class to search */
};
以上,如有问题,请指正,感谢。