NSObject 是 Objective-C 類別體系中的根類別,它提供了兩個與訊息轉發相關的關鍵方法。當呼叫某個物件不存在的方法時,執行期會把這個呼叫封裝成 NSInvocation 物件,嘗試傳遞給 forwardInvocation:;若該物件有重載此方法,就能攔截下來做自訂處理。
相較之下,forwardingTargetForSelector: 的用途從官方描述看起來比較抽象,實際在動手做反射相關處理(例如把 JSON 資料源對映到物件的 O-R Mapping)時才會真正用得上。
回傳未知訊息應首先轉向的物件。
Returns the object to which unrecognized messages should first be directed.
- (id)forwardingTargetForSelector:(SEL)aSelector
由子類重載,用於把訊息前轉給其他物件。
Overridden by subclasses to forward messages to other objects.
- (void)forwardInvocation:(NSInvocation *)anInvocation
下面的做法讓物件在被呼叫未知方法時,先問問 friend 這個物件能不能處理;可以就轉給它,不行才交回父類別走預設流程(最終會拋出 doesNotRecognizeSelector 異常):
- (void)forwardInvocation:(NSInvocation *)invocation {
SEL orignalSelector = [invocation selector];
if ([friend respondsToSelector:orignalSelector]) {
[invocation invokeWithTarget:friend];
} else {
[super forwardInvocation:invocation];
}
}
訊息轉發的代價並不低——它會經歷 signature 查詢、NSInvocation 封裝、方法解析等多個階段,比正常的方法呼叫慢得多,因此不適合放在高效能路徑上。
另外,若你重載了 forwardingTargetForSelector: 或 forwardInvocation:,也應該同時實作 methodSignatureForSelector:,否則在建立 NSInvocation 的階段就會失敗,根本走不到轉發邏輯。
實務上這套機制最常見的三個用途是:建立代理型別的「訊息轉發」模式、把事件轉給內部持有的物件,以及做輕量的動態特性模擬(例如 iOS 8 以前的 to-many relationship 操作)。