OC - Runtime 一點(diǎn)思考

class_addMethod
1.Sel在 class 中有實(shí)現(xiàn)了就不能成功; Sel在class中沒(méi)有Imp就能添加成功(即使有定義)
2.class單指本類,和superclass無(wú)關(guān) (即使superClass 實(shí)現(xiàn)了Sel,也可以添加成功)

method_getImplementation
獲取的實(shí)時(shí)的Imp

super (self中的super調(diào)用還是本身,和super本質(zhì)有關(guān))

struct objc_super { id receiver; Class superClass; };

receiver --> 當(dāng)前類 (self)
superClass ---> 這個(gè)類的父類

實(shí)際上只是一個(gè)”編譯器標(biāo)示符”,它負(fù)責(zé)告訴編譯器,當(dāng)調(diào)用viewDidLoad方法時(shí),去調(diào)用父類的方法,而不是本類中的方法。
不是調(diào)用objc_msgSend函數(shù),而是調(diào)用objc_msgSendSuper函數(shù)
id objc_msgSendSuper ( struct objc_super *super, SEL op, ... );

特殊情況:

  1. [obj performSelector:@select(method)] 和 [obj method] 意思一致,可是調(diào)用本質(zhì)上不一樣。
    特別是obj --> super
    說(shuō)明:
    [super viewDidLoad] 調(diào)用的是superClass的方法, 數(shù)據(jù)是Self
    [super performSelector:@select(viewDidLoad)] 調(diào)用的是self的方法 (respondsToSelector 也是同效果)

    所以不要用:
    super, respondsToSelector和performSelector 組合, 會(huì)形成死循環(huán)

  1. 可能調(diào)用的是 super performSelector ; performSelector 中的方法中調(diào)用的是 subClass類的實(shí)現(xiàn)
  2. 用 self去調(diào)用 super的Sel的Imp (self 提供的數(shù)據(jù))

[super respondsToSelector:@selsector(methodOnlyInSub)]

objc_msgSendSuper(objc_super *super, @selector(respondsToSelector:) ) --> 判斷出super有

--> 可能 objc_msgSend(objc_super.receiver, @selector(respondsToSelector:)) = objc_msgSend(self,@selector(respondsToSelector:)) --> 在 respondsToSelector 方法里,就成了
objc_msgSend(self, @(methodOnlyInSub)) 在self 類方法中找實(shí)現(xiàn)

調(diào)用 objc_msgSendSuper 的方法,將這個(gè)結(jié)構(gòu)體和 respondsToSelector 的 sel 傳遞過(guò)去。函數(shù)里面在做的事情類似這樣:從 objc_super 結(jié)構(gòu)體指向的 superClass 的方法列表開(kāi)始找 respondsToSelector 的 selector,找到后再以 objc_super->receiver 去調(diào)用這個(gè) selector,可能也會(huì)使用 objc_msgSend 這個(gè)函數(shù),不過(guò)此時(shí)的第一個(gè)參數(shù) theReceiver 就是 objc_super->receiver,第二個(gè)參數(shù)是從 objc_super->superClass 中找到的 selector

參考
https://blog.csdn.net/likendsl/article/details/44085569

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書(shū)系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

  • 轉(zhuǎn)至元數(shù)據(jù)結(jié)尾創(chuàng)建: 董瀟偉,最新修改于: 十二月 23, 2016 轉(zhuǎn)至元數(shù)據(jù)起始第一章:isa和Class一....
    40c0490e5268閱讀 2,068評(píng)論 0 9
  • runtime 和 runloop 作為一個(gè)程序員進(jìn)階是必須的,也是非常重要的, 在面試過(guò)程中是經(jīng)常會(huì)被問(wèn)到的, ...
    made_China閱讀 1,273評(píng)論 0 7
  • 我們常常會(huì)聽(tīng)說(shuō) Objective-C 是一門(mén)動(dòng)態(tài)語(yǔ)言,那么這個(gè)「動(dòng)態(tài)」表現(xiàn)在哪呢?我想最主要的表現(xiàn)就是 Obje...
    Ethan_Struggle閱讀 2,340評(píng)論 0 7
  • 繼上Runtime梳理(四) 通過(guò)前面的學(xué)習(xí),我們了解到Objective-C的動(dòng)態(tài)特性:Objective-C不...
    小名一峰閱讀 848評(píng)論 0 3
  • runtime 和 runloop 作為一個(gè)程序員進(jìn)階是必須的,也是非常重要的, 在面試過(guò)程中是經(jīng)常會(huì)被問(wèn)到的, ...
    SOI閱讀 22,025評(píng)論 3 63

友情鏈接更多精彩內(nèi)容