您现在的位置: IOS教程網 >> IOS系統 >  >> iOS 程式開發 >> iOS 程式設計技術

Objective-C Runtime 入門:核心結構與三大實務應用

編輯:iOS 程式設計技術

專案裡常會用到 runtime 的功能模組。就日常開發而言,其實不必啃源碼,把常用函式與背後原理理解清楚就夠用了。但若能靜下心讀一遍源碼,對 objc 本身的機制以及那些高階語法糖,理解會深得多。

什麼是 runtime

runtime 就是「執行期」,每種語言都有自己的 runtime,差別在於執行期有多少彈性。

C 語言在編譯階段就決定了要呼叫哪些函式,編譯完就照表執行,沒有二義性,因此屬於靜態語言。Objective-C 的函式調用則可以理解為「送訊息」:編譯時無法確定哪個函式會被執行,只有到執行期才依 selector 找到對應實作。正因如此,它能在執行中動態增替方法與屬性,屬於動態語言。

動態與靜態其實沒有明確界線,我個人是用「runtime 有多靈活」來判斷一门語言有多動態。

核心結構

Method

struct objc_method {
    SEL method_name;
    char *method_types;
    IMP method_imp;
};

SEL 本質上是字串,可理解為函式的名字;IMP 是函式指標,指向真正的實作。類別的 method list 保存了 SEL 到 IMP 的對應關係,因此給定 SEL 就能找到實作。

Ivar

struct objc_ivar {
    char *ivar_name;
    char *ivar_type;
    int ivar_offset;
};

實例變數,與特定物件關聯,無法在類別方法中直接使用;與之相對的是類變數。

Category

struct objc_category {
    char *category_name;
    char *class_name;
    struct objc_method_list *instance_methods;
    struct objc_method_list *class_methods;
    struct objc_protocol_list *protocols;
};

Category 能為已存在的類別動態加入新方法(實例方法、類別方法、協議)。從結構可看出它無法加入屬性與實例變數——這正是後面「關聯物件」要解決的問題。

objc_class 與 method cache

struct objc_class {
    Class isa;                            // 實例的 isa 指向類別,類別的 isa 指向元類
    Class super_class;                    // 指向父類
    const char *name;                     // 類別名稱
    long version;
    long info;
    long instance_size;
    struct objc_ivar_list *ivars;         // 成員變數清單
    struct objc_method_list **methodLists;// 方法清單
    struct objc_cache *cache;             // 方法快取
    struct objc_protocol_list *protocols; // 協議清單
};

其中 objc_cache 存放最近呼叫過的方法,每次送訊息時先查快取,命中就不必遍歷 method list,這是 objc 訊息分發效能的關鍵優化。

應用一:取得類別資訊(字典轉模型)

class_copyPropertyList // 屬性清單
class_copyMethodList  // 方法清單
class_copyIvarList   // 成員變數清單
class_copyProtocolList // 協議清單
@interface LYUser : NSObject
@property (nonatomic, strong) NSString *userId;
@property (nonatomic, strong) NSString *userName;
@property (nonatomic, strong) NSString *age;
@end

- (void)viewDidLoad {
    [super viewDidLoad];

    NSDictionary *userDict = @{@"userId": @"1", @"userName": @"levi", @"age": @"20"};

    unsigned int count = 0;
    LYUser *user = [LYUser new];

    objc_property_t *props = class_copyPropertyList([LYUser class], &count);
    for (NSUInteger i = 0; i < count; i++) {
        const char *name = property_getName(props[i]);
        NSString *key = [NSString stringWithUTF8String:name];
        if (userDict[key]) {
            [user setValue:userDict[key] forKey:key];
        }
    }
    free(props);  // copy 系列函式回傳的記憶體需自行釋放

    NSLog(@"%@ - %@ - %@", user.userId, user.userName, user.age);
}

這只是最陽春的版本,實務上還要考慮型別轉換、鍵值不符的容錯、以及效能。市面上已有不少開源模型轉換庫把這些細節處理得很好,效能差異也有相關評測可參考。

應用二:方法交換(Swizzling)

class_getInstanceMethod() // 取得實例方法
class_getClassMethod()   // 取得類別方法(兩者存放位置不同,故分開)
method_exchangeImplementations() // 交換兩個方法的實作

這個技巧能大幅減少重複程式碼,常見用途有防錯、統計埋點、統一調整 UI。

(1)防錯:攔截 nil 加入陣列

-(void)viewDidLoad {
    [super viewDidLoad];

    NSMutableArray *arr = [NSMutableArray new];
    [arr addObject:@"1"];
    NSString *nilStr = nil;
    [arr addObject:nilStr];   // 一般情況會 crash

    for (NSInteger i = 0; i < arr.count; i++) {
        NSLog(@"%@", arr[i]);
    }
}

@implementation NSMutableArray (ErrorLog)

+ (void)load {
    Method origin = class_getInstanceMethod(NSClassFromString(@"__NSArrayM"),
                                            @selector(addObject:));
    Method custom = class_getInstanceMethod(NSClassFromString(@"__NSArrayM"),
                                            @selector(el_addObject:));
    method_exchangeImplementations(origin, custom);
}

// 交換之後,這個方法裡的 self el_addObject: 實際呼叫的是原本 addObject:
- (void)el_addObject:(id)object {
    if (object) {
        [self el_addObject:object];
    } else {
        NSLog(@"嘗試將 nil 加入陣列");
    }
}

@end

(2)統計埋點

寫法完全相同,在對應類別的 Category 的 +load 中交換即可。

// 頁面出現統計
Method origin = class_getInstanceMethod([self class], @selector(viewDidLoad));
Method custom = class_getInstanceMethod([self class], @selector(el_viewDidLoad));
method_exchangeImplementations(origin, custom);

// 按鈕點擊統計
Method origin2 = class_getInstanceMethod([self class],
                                         @selector(sendAction:to:forEvent:));
Method custom2 = class_getInstanceMethod([self class],
                                         @selector(el_sendAction:to:forEvent:));
method_exchangeImplementations(origin2, custom2);

(3)統一調整 UI

專案前期通常先做邏輯,顏色與細節留到最後。等到要改 cell 右箭頭的間距、placeholder 的預設色時,一處一處改既麻煩又容易漏。這時 runtime 就很好用。

+ (void)load {
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        Class cls = [self class];
        Method origin = class_getInstanceMethod(cls, @selector(layoutSubviews));
        Method custom = class_getInstanceMethod(cls, @selector(swizzling_layoutSubviews));
        method_exchangeImplementations(origin, custom);
    });
}

// 統一 cell 右側箭頭樣式
- (void)setAccessoryType:(UITableViewCellAccessoryType)accessoryType {
    if (accessoryType == UITableViewCellAccessoryDisclosureIndicator) {
        UIImageView *arrow = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"arrow"]];
        arrow.centerY = self.centerY;
        arrow.right = self.width - 16;
        self.accessoryView = arrow;
    } else if (accessoryType == UITableViewCellAccessoryNone) {
        self.accessoryView = nil;
    }
}

// 統一 cell 內距
- (void)swizzling_layoutSubviews {
    [self swizzling_layoutSubviews];   // 交換後這行呼叫的是原本實作

    if (self.imageView.image) {
        self.imageView.origin = CGPointMake(16, self.imageView.origin.y);
        self.textLabel.origin = CGPointMake(CGRectGetMaxX(self.imageView.frame) + 10,
                                            self.textLabel.origin.y);
    } else {
        self.textLabel.origin = CGPointMake(16, self.textLabel.origin.y);
    }
    self.textLabel.width = MIN(self.textLabel.width, 180);
    self.accessoryView.right = self.width - 16;
}

使用 Swizzling 有兩點務必注意:一定要在 +load 中執行並搭配 dispatch_once,避免多次交換;交換後要小心遞迴呼叫,方法內呼叫的「自己」其實是對方原本的實作。

應用三:關聯物件

objc_setAssociatedObject(id object, const void *key, id value, objc_AssociationPolicy policy)
objc_getAssociatedObject(id object, const void *key)

前面提過 Category 無法加入屬性,而關聯物件正好填補這個空缺,讓你在執行期為既有類別動態掛上值。對封裝很有幫助。

以「限制 textField 輸入長度」為例:每個地方都在 delegate 裡重寫一次太醜,自訂子類別又嫌麻煩,用關聯物件就能優雅解決。

// UITextField+TextRange.h
@interface UITextField (TextRange)
@property (nonatomic, assign) NSInteger maxLength;
@end

// UITextField+TextRange.m
- (void)dealloc {
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}

- (void)setMaxLength:(NSInteger)maxLength {
    objc_setAssociatedObject(self, KTextFieldMaxLength, @(maxLength),
                             OBJC_ASSOCIATION_RETAIN_NONATOMIC);
    [self textField_addTextDidChangeObserver];
}

- (NSInteger)maxLength {
    return [objc_getAssociatedObject(self, KTextFieldMaxLength) integerValue];
}

- (void)textField_addTextDidChangeObserver {
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(textDidChange:)
                                                 name:UITextFieldTextDidChangeNotification
                                               object:self];
}

- (void)textDidChange:(NSNotification *)notification {
    UITextField *textField = notification.object;

    if (textField.text.length > self.maxLength) {
        UITextRange *markedRange = [textField markedTextRange];
        UITextPosition *position = [textField positionFromPosition:markedRange.start offset:0];

        // 中文輸入法的候選字階段不處理,否則會截斷拼音
        if (!position) {
            UITextRange *selectedRange = textField.selectedTextRange;
            textField.text = [textField.text subStringWithMaxLength:self.maxLength];
            textField.selectedTextRange = selectedRange;
        }
    }
}

以上大致涵蓋 runtime 最常用的幾塊。我也還在學習中,會持續補充。

最後分享一個讀源碼的小方法:直接去 GitHub 搜尋 #import <objc/runtime.h>,能看到大量實際案例。比起硬啃源碼,從應用實例回推原理,目標明確得多。

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