上手 iOS 開發一段時間後會發現,只埋頭完成需求成長有限,利用空檔研究 Runtime 這類底層機制,才是深入平台的正途。本文從最基礎的 class_addMethod 談起。
/** * Adds a new method to a class with a given name and implementation. * * @param cls The class to which to add a method. * @param name A selector that specifies the name of the method being added. * @param imp A function which is the implementation of the new method. * The function must take at least two arguments—self and _cmd. * @param types An array of characters that describe the types of the * arguments to the method. * * @return YES if the method was added successfully, otherwise NO * (for example, the class already contains a method * implementation with that name). * * @note class_addMethod will add an override of a superclass's implementation, * but will not replace an existing implementation in this class. * To change an existing implementation, use method_setImplementation. */ OBJC_EXPORT BOOL class_addMethod(Class cls, SEL name, IMP imp, const char *types);
self 與 _cmd 兩個參數。另外要注意文件的 @note:class_addMethod 只能「覆寫父類實作」或「新增方法」,無法取代所屬類中已存在的實作。若目標是置換既有方法,應該改用 method_setImplementation。
Objective-C 是動態語言,部分行為在執行期而非編譯期決定,因此除了編譯器,還需要 Runtime 環境。常見的兩個使用時機:
Objective-C 的方法呼叫本質是發送訊息。當類中找不到該方法時,系統會進入「找不到方法的處理流程」,而我們可以在這個流程中補上動態添加的邏輯。相關的兩個入口是:
+ (BOOL)resolveInstanceMethod:(SEL)sel; // 實例方法 + (BOOL)resolveClassMethod:(SEL)sel; // 類方法
先建立 Car 的分類 myCar:
#import "Car+myCar.h" @implementation Car (myCar) @end
#import "Car+myCar.h"
void startEngine(id self, SEL _cmd) {
NSLog(@"my car starts the engine");
}
@implementation Car (myCar)
@end
需要額外參數時,接在必要參數之後即可;要回傳值則把 void 換成目標型別:
void startEngine(id self, SEL _cmd, NSString *brand) {
NSLog(@"my %@ car starts the engine", brand);
}
#import "Car+myCar.h"
#import <objc/runtime.h>
void startEngine(id self, SEL _cmd, NSString *brand) {
NSLog(@"my %@ car starts the engine", brand);
}
@implementation Car (myCar)
+ (BOOL)resolveInstanceMethod:(SEL)sel {
if (sel == @selector(drive)) {
class_addMethod([self class], sel, (IMP)startEngine, "v@:@");
return YES;
}
return [super resolveInstanceMethod:sel];
}
@end
這個方法會在 Runtime 找不到該方法實作時被呼叫。先比對傳入的 SEL,命中就呼叫 class_addMethod:第三個參數傳入我們的 C 函式,第四個參數 "v@:@" 表示回傳 void、參數為 self 與一個物件型別參數。回傳值實測不影響結果,一般回 YES 即可。
若不習慣 C 函式,可以改用 class_getMethodImplementation 取得既有方法的 IMP:
@implementation Car (myCar)
+ (BOOL)resolveInstanceMethod:(SEL)sel {
if (sel == @selector(drive)) {
class_addMethod([self class], sel,
class_getMethodImplementation(self, @selector(startEngine:)), "v@:@");
return YES;
}
return [super resolveInstanceMethod:sel];
}
- (void)startEngine:(NSString *)brand {
NSLog(@"my %@ car starts the engine", brand);
}
@end
建立一個新類別 DynamicSelector 來觸發:
#import "DynamicSelector.h"
#import "Car+myCar.h"
@implementation DynamicSelector
- (void)dynamicAddMethod {
Car *c = [[Car alloc] init];
// 不能用 [c drive],編譯期找不到該方法會直接報錯
[c performSelector:@selector(drive) withObject:@"bmw"];
}
@end
執行結果:
2016-08-26 10:50:17.207 objc-runtime[76618:3031897] my bmw car starts the engine Program ended with exit code: 0
[c drive] 會產生警告甚至錯誤。performSelector:withObject: 把方法查找延後到執行期,才能命中我們動態註冊的實作。"v@:@" 中的 v 是 void 回傳、@ 是 id、: 是 SEL。若參數型別寫錯,雖然編譯不會報錯,執行時卻可能出現參數錯位或未定義行為。class_addMethod 是通往 Runtime 世界的一張入門票,真正的價值在於理解「方法查找」這件事本身。理解了 Message Forwarding,後續的 Method Swizzling、消息轉發(forwardInvocation)、關聯物件等技術都會變得順理成章。若有疑問歡迎留言討論。