探究Objective-C中self 與super的區(qū)別與底層實現(xiàn)原理

1、self和super關鍵字解釋?

(1)官方文檔中self相關解釋:

Whenever you’re writing a method implementation, you have access to an important hidden value, self. Conceptually, self is a way to refer to “the object that’s received this message.” It’s apointer, just like the greeting value above, and can be used to call a method on the current receiving object.

(2)官方文檔中super相關解釋:

There’s anotherimportant keyword available to you in Objective-C, called super. Sending a message to super is a way to call through to a method implementation defined by a superclass further up the inheritance chain. The most common use of super is when overriding a method.

蘋果官方文檔中明確說明self調用自身的方法,super調用父類的方法,也就是說,用self進行方法調用,會先從自身的方法列表中開始查找,如果沒有再從父類的方法里列表中查找,super則一開始就從父類的方法列表中開始查找;由此可見super調用在某種情況下會更加快速
注意,self和super進行方法調用只是在查找方法的起始順序不同,但消息的接收者是一樣的,都是當前的self;下面我們來進行探究驗證:

2.探究self調用方法與super調用方法的區(qū)別?

//JSPerson.m的實現(xiàn)
@implementation JSPerson
-(instancetype)init{
    self = [super init];
    if (self) {
        NSLog(@"%@-%@",[self class],[super class]);
    }
    return self;
}

//main.m的實現(xiàn)
int main(int argc, const char * argv[]) {
    @autoreleasepool {
        // insert code here...
        JSPerson *person = [[JSPerson alloc] init];
    }
    return 0;
}

要探究其底層實現(xiàn),我們可以利用clang命令將其編譯成.cpp文件
進入當前JSPerson.m文件目錄
終端執(zhí)行:clang -rewrite-objc JSPerson.m -o JSPerson.cpp
生成JSPerson.cpp的C++文件,部分代碼如下:

// @implementation JSPerson

static instancetype _I_JSPerson_init(JSPerson * self, SEL _cmd) {
    self = ((JSPerson *(*)(__rw_objc_super *, SEL))(void *)objc_msgSendSuper)((__rw_objc_super){(id)self, (id)class_getSuperclass(objc_getClass("JSPerson"))}, sel_registerName("init"));
    if (self) {
        NSLog((NSString *)&__NSConstantStringImpl__var_folders_q9_m967z0vn5js5qqnp7gbfdwq80000gn_T_JSPerson_7c19d1_mi_0,((Class (*)(id, SEL))(void *)objc_msgSend)((id)self, sel_registerName("class")),
        ((Class (*)(__rw_objc_super *, SEL))(void *)objc_msgSendSuper)((__rw_objc_super){(id)self, (id)class_getSuperclass(objc_getClass("JSPerson"))}, sel_registerName("class")));
    }
    return self;
}

[self class] 對應C++的代碼: ((Class (*)(id, SEL))(void *)objc_msgSend)((id)self, sel_registerName("class"))

[super class]對應C++的代碼:((Class (*)(__rw_objc_super *, SEL))(void *)objc_msgSendSuper)((__rw_objc_super){(id)self, (id)class_getSuperclass(objc_getClass("JSPerson"))}, sel_registerName("class")

查看OC源碼中objc_msgSend和objc_msgSendSuper方法的聲明如下:
objc_msgSend(void /* id self, SEL op, ... */ )
    OBJC_AVAILABLE(10.0, 2.0, 9.0, 1.0, 2.0);
    
OBJC_EXPORT void
objc_msgSendSuper(void /* struct objc_super *super, SEL op, ... */ )
    OBJC_AVAILABLE(10.0, 2.0, 9.0, 1.0, 2.0);

由此可見編譯器對super關鍵字的處理是構建的一個objc_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 is the first class to search */
};

可以看到objc_super結構體內部有一個receiver和super_class的成員,receiver存儲消息的接收者,而我們查看[super class]對應的C++代碼中發(fā)現(xiàn)objc_msgSendSuper的第一個參數(shù)是(__rw_objc_super){(id)self, (id)class_getSuperclass(objc_getClass("JSPerson"))}結構體,也就是super_class,其第一個參數(shù)接收的是(id)self,賦值給內部的receiver成員,
從這里可以明確分析出objc_msgSendSuper的第一個參數(shù)是super_class結構體指針,而super_class內部結構的第一個成員變量receiver存儲的是從外部接收進來的(id)self,根據指針的訪問我們可以知道objc_msgSendSuper的接收者也是self

 結論:NSLog(@"%@-%@",[self class],[super class])打印的結果為:JSPerson-JSPerson
 
 蘋果為什么要實現(xiàn)這樣的super邏輯?
    . 個人觀點是可以加快方法的查找,iOS中方法的查找是從子類到父類再到NSObject根類的一個流程,使用super可以直接定位到父類的方法開始查找,省去了子類的查找環(huán)節(jié)
?著作權歸作者所有,轉載或內容合作請聯(lián)系作者
【社區(qū)內容提示】社區(qū)部分內容疑似由AI輔助生成,瀏覽時請結合常識與多方信息審慎甄別。
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發(fā)布,文章內容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務。

相關閱讀更多精彩內容

友情鏈接更多精彩內容