您现在的位置: IOS教程網 >> IOS系統 >  >> iOS 程式開發 >> iOS 開發綜合

iOS Runtime 動態添加方法並呼叫:class_addMethod 詳解

編輯:iOS 開發綜合

前言

上手 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);

二、四個參數各自的意義

  • Class cls:要添加方法的目標類。
  • SEL name:方法名(selector),可依需求自行命名。
  • IMP imp:implementation,編譯器生成、指向實作函式的指標。這個函式至少要包含 self 與 _cmd 兩個參數。
  • const char *types:描述回傳值與參數型別的編碼字串。

另外要注意文件的 @note:class_addMethod 只能「覆寫父類實作」或「新增方法」,無法取代所屬類中已存在的實作。若目標是置換既有方法,應該改用 method_setImplementation。

三、什麼時候會用到

Objective-C 是動態語言,部分行為在執行期而非編譯期決定,因此除了編譯器,還需要 Runtime 環境。常見的兩個使用時機:

  1. 繼承某個類,但父類沒有提供你需要的方法,而你又不清楚父類內部實作。
  2. 為某個類寫分類(Category),需要在其中動態新增或替換方法(注意:不建議在分類中重寫既有方法,也無法用 super 取得「父類」實作)。

四、關鍵機制:Message Forwarding

Objective-C 的方法呼叫本質是發送訊息。當類中找不到該方法時,系統會進入「找不到方法的處理流程」,而我們可以在這個流程中補上動態添加的邏輯。相關的兩個入口是:

+ (BOOL)resolveInstanceMethod:(SEL)sel;   // 實例方法
+ (BOOL)resolveClassMethod:(SEL)sel;     // 類方法

五、完整實作

先建立 Car 的分類 myCar:

#import "Car+myCar.h"

@implementation Car (myCar)
@end

步驟一:寫出要動態添加的實作(C 函式風格)

#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);
}

步驟二:重載 resolveInstanceMethod:

#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 即可。

比較 Objective-C 風格的寫法

若不習慣 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

六、兩個實務提醒

  • 為什麼必须用 performSelector:動態添加的方法在編譯期不存在,直接寫 [c drive] 會產生警告甚至錯誤。performSelector:withObject: 把方法查找延後到執行期,才能命中我們動態註冊的實作。
  • type encoding 要正確。"v@:@" 中的 v 是 void 回傳、@ 是 id、: 是 SEL。若參數型別寫錯,雖然編譯不會報錯,執行時卻可能出現參數錯位或未定義行為。

總結

class_addMethod 是通往 Runtime 世界的一張入門票,真正的價值在於理解「方法查找」這件事本身。理解了 Message Forwarding,後續的 Method Swizzling、消息轉發(forwardInvocation)、關聯物件等技術都會變得順理成章。若有疑問歡迎留言討論。

  1. 上一篇文章:
  2. 下一篇文章:
蘋果刷機越獄教程| IOS教程問題解答| IOS技巧綜合| IOS7技巧| IOS8教程
Copyright © IOS教程網 All Rights Reserved