項目中不少功能模塊都會用到 runtime。對於要不要讀源碼,我的看法是:僅僅為了應付日常開發,把常用 API 和基本原理搞明白足夠;但如果能靜下心把源碼讀一遍,對理解 Objective-C 本身以及那些高階封裝出來的「魔法」會有質的幫助。
runtime 就是運行時,每門語言都有。通俗講就是程序跑起來之後發生的事情。
C 語言在編譯期就確定了調用哪些函數,編譯完一路執行下去,沒有二義性,因此被視為靜態語言。而 Objective-C 的方法調用可以理解為「發消息」:編譯期無法確定最終執行哪個函數實現,只有運行時才根據方法名去查找,因此可以在運行期動態添加、替換方法和屬性,是典型的動態語言。
動態與靜態之間並沒有涇渭分明的界線,我理解就是以 runtime 表現有多靈活來衡量。
typedef struct objc_method *Method;
struct objc_method {
SEL method_name; // 方法名
char *method_types; // 類型編碼
IMP method_imp; // 函數實現
};
SEL 本質是字符串指針,可理解為函數的「姓名」;IMP 是函數指針,指向真正的實現。類對象的 method list 保存了 SEL 到 IMP 的映射,所以通過 SEL 就能找到實現。
typedef struct objc_ivar *Ivar;
struct objc_ivar {
char *ivar_name;
char *ivar_type;
int ivar_offset;
};
實例變量,與具體對象關聯,不能被類方法直接訪問。
typedef struct objc_category *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 可以在運行期為已存在的類添加行為,包括實例方法、類方法和協議。但從結構可見,它無法添加實例變量與屬性——這也是為什麼 Category 裡加屬性必須配合關聯對象。
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 保存最近調用過的方法,每次發消息先查緩存再查方法列表,這是 runtime 的性能優化手段。
獲取類信息:
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;
LYUser *newUser = [LYUser new];
objc_property_t *propertyList = class_copyPropertyList([LYUser class], &count);
for (int i = 0; i < count; i++) {
const char *propertyName = property_getName(propertyList[i]);
NSString *key = [NSString stringWithUTF8String:propertyName];
[newUser setValue:userDict[key] forKey:key];
}
NSLog(@"%@--%@--%@", newUser.userId, newUser.userName, newUser.age);
}

這只是最樸素的版本,真要上線還得處理類型不匹配、嵌套模型、駝峰下劃線映射與轉換效率,目前開源社區已有不少成熟方案可供參考。
交換方法實現:
class_getInstanceMethod() // 取得實例方法 class_getClassMethod() // 取得類方法 method_exchangeImplementations() // 交換兩個方法的實現
這是用得最多的能力,能大幅減少重複代碼。常見場景有三類。
防錯措施——攔截數組插入 nil:
@implementation NSMutableArray (ErrorLog)
+ (void)load {
Method originAddMethod = class_getInstanceMethod(NSClassFromString(@"__NSArrayM"), @selector(addObject:));
Method newAddMethod = class_getInstanceMethod(NSClassFromString(@"__NSArrayM"), @selector(el_addObject:));
method_exchangeImplementations(originAddMethod, newAddMethod);
}
- (void)el_addObject:(id)object {
if (object != nil) {
[self el_addObject:object]; // 交換後這裡實際執行的是原方法
} else {
NSLog(@"數組添加了 nil");
}
}
@end

統計打點——方式一致,在對應類的 Category 的 load 裡交換,可無侵入地統計頁面出現與按鈕點擊:
// 統計頁面出現 Method originAddMethod = class_getInstanceMethod([self class], @selector(viewDidLoad)); Method newAddMethod = class_getInstanceMethod([self class], @selector(el_ViewDidLoad)); method_exchangeImplementations(originAddMethod, newAddMethod); // 統計按鈕點擊 Method originAddMethod2 = class_getInstanceMethod([self class], @selector(sendAction:to:forEvent:)); Method newAddMethod2 = class_getInstanceMethod([self class], @selector(el_sendAction:to:forEvent:)); method_exchangeImplementations(originAddMethod2, newAddMethod2);
統一調整界面細節——項目前期先做邏輯,界面細節最後統一處理,此時逐個改動既費時又易漏,runtime 剛好勝任:
+ (void)load {
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
Class class = [self class];
SEL originalSelector = @selector(layoutSubviews);
SEL swizzledSelector = @selector(swizzling_layoutSubviews);
Method originalMethod = class_getInstanceMethod(class, originalSelector);
Method swizzledMethod = class_getInstanceMethod(class, swizzledSelector);
method_exchangeImplementations(originalMethod, swizzledMethod);
});
}
// 統一 cell 右側箭頭樣式
- (void)setAccessoryType:(UITableViewCellAccessoryType)accessoryType {
if (accessoryType == UITableViewCellAccessoryDisclosureIndicator) {
UIImageView *accessoryView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"about_arrow_icon"]];
accessoryView.centerY = self.centerY;
accessoryView.right = self.width - 16;
self.accessoryView = accessoryView;
} 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;
}
關聯對象:
objc_setAssociatedObject(id object, const void *key, id value, objc_AssociationPolicy policy); objc_getAssociatedObject(id object, const void *key);
既然 Category 不能添加屬性,關聯對象就提供了運行期動態掛載存儲的途徑。以 textField 長度限制為例,過去要麼在每個 delegate 裡重複代碼,要麼自定義子類,用關聯對象則能優雅解決:
// .h
@interface UITextField (TextRange)
@property (nonatomic, assign) NSInteger maxLength;
@end
// .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(textField_textDidChange:)
name:UITextFieldTextDidChangeNotification
object:self];
}
- (void)textField_textDidChange:(NSNotification *)notification {
UITextField *textField = notification.object;
NSString *text = textField.text;
MYTitleInfo titleInfo = [text getInfoWithMaxLength:self.maxLength];
if (titleInfo.length > self.maxLength) {
UITextRange *selectedRange = [textField markedTextRange];
UITextPosition *position = [textField positionFromPosition:selectedRange.start offset:0];
// 有標記文本(如拼音輸入中)時不截斷,避免打斷輸入
if (!position) {
UITextRange *textRange = textField.selectedTextRange;
textField.text = [textField.text subStringWithMaxLength:self.maxLength];
textField.selectedTextRange = textRange;
}
}
}
以上就是 runtime 最常用的幾塊內容。最後分享一個學習小技巧:直接翻源碼確實枯燥,可以去 GitHub 搜索 import <objc/runtime.h>,看看優秀項目都拿它做了什麼,帶著目標去讀會有動力得多。