objective c runtime 分享2

22
Objective-C Runtime DaidoujiChen 20150806

Upload: jeff-lee

Post on 15-Aug-2015

95 views

Category:

Mobile


0 download

TRANSCRIPT

Objective-C Runtime DaidoujiChen 20150806

Review

2

Review

• 快速的回顧⼀一下, 在⼀一個 message ⾛走到 doesNotRecognizeSelector: 會經過三個挽救的機會.

Review1. + (BOOL)resolveInstanceMethod:(SEL)name; 2. - (id)forwardingTargetForSelector:(SEL)aSelector;

3. -(NSMethodSignature*)methodSignatureForSelector:(SEL)aSelector; - (void)forwardInvocation:(NSInvocation *)anInvocation;

Message

5

Message

幾乎每⼀一本基礎的 Objective-C 書裡⾯面都會講到, 所有的 Method 運⾏行調⽤用, 都可以視為

[reciver message];

Message

reciver 是要運⾏行這個 Method 的 Object message 則是要被運⾏行的 Method name

ex: [normalObject invoke]; [NormalObject randomIntegerValue];

Message

然⽽而, 確切要運⾏行的 reciver 是哪個 Object, compiler 並不知道, 真正由誰來執⾏行, 在 Runtime 的時候才會決定.

Messagecompiler 只會將 Method 轉化為

[normalObject invoke]; to objc_msgSend(normalObject, @selector(invoke));

Message

[NormalObject randomIntegerValue]; to objc_msgSend([NormalObject class], @selector(randomIntegerValue));

Message

關於 objc_msgSend 做了什麼, 官⽅方網站這樣告訴我們.

Message1. It first finds the procedure (method implementation) that the selector refers to. Since the same method can be implemented differently by separate classes, the precise procedure that it finds depends on the class of the receiver.

Message2. It then calls the procedure, passing it the receiving object (a pointer to its data), along with any arguments that were specified for the method.

Message3. Finally, it passes on the return value of the procedure as its own return value.

Message

Message

實際上, objc_msgSend ⼤大致上分為幾個動作

Message

1. 檢查 reciver 是否為 nil

Message

2. 檢查這個 method 的 IMP 是不是已經存在 class 的 cache

Message3. 如果不存在, 則會⼀一直向上查找.

Message

Q&A

ReferenceObjective-C Runtime Programming Guide

A Look Under the Hood of objc_msgSend()

Chapter 4 Assembly Language