
作者:興宇是誰,授權本站轉載。
想要真正吃透 Objective-C,Runtime 是繞不過去的一課。筆者近期系統學習了 Runtime,將心得整理成文,一方面方便日後查閱,另一方面也希望拋磚引玉,歡迎大家指正不足。
我們寫下的每一行代碼,在運行時最終都會被轉化為 Runtime 的 C 代碼來執行。例如 [target doSomething]; 會被轉換成 objc_msgSend(target, @selector(doSomething));。
OC 中幾乎一切都是對象。我們都知道類被初始化後得到的是一個實例對象,而實際上,類本身在本質上也是一個對象,只不過它在 Runtime 中是以結構體的形式存在的。
/// 描述類中的一個方法 typedef struct objc_method *Method; /// 實例變量 typedef struct objc_ivar *Ivar; /// 類別 Category typedef struct objc_category *Category; /// 類中聲明的屬性 typedef struct objc_property *objc_property_t;
類在 Runtime 中的表示如下:
// 類在 runtime 中的表示 struct objc_class { Class isa; // 指針,顧名思義表示是一個什麼 // 實例的 isa 指向類對象,類對象的 isa 指向元類 #if !__OBJC2__ 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 // 協議列表 #endif } OBJC2_UNAVAILABLE;開發中有時會遇到這樣的需求:需要拿到當前類所有屬性的名字,比如做字典轉模型時,字典的 Key 與模型屬性名並不一致。此時可以借助 Runtime 提供的一系列方法,獲取類的屬性列表、方法列表、成員變量列表以及遵循的協議列表。
unsigned int count; // 獲取屬性列表 objc_property_t *propertyList = class_copyPropertyList([self class], &count); for (unsigned int i=0; i%@", [NSString stringWithUTF8String:propertyName]); } // 獲取方法列表 Method *methodList = class_copyMethodList([self class], &count); for (unsigned int i; i %@", NSStringFromSelector(method_getName(method))); } // 獲取成員變量列表 Ivar *ivarList = class_copyIvarList([self class], &count); for (unsigned int i; i %@", [NSString stringWithUTF8String:ivarName]); } // 獲取協議列表 __unsafe_unretained Protocol **protocolList = class_copyProtocolList([self class], &count); for (unsigned int i; i %@", [NSString stringWithUTF8String:protocolName]); }
建議在 Xcode 裡實際跑一下觀察輸出。需要注意的是,你得先給當前類寫上若干屬性、成員變量、方法和協議,否則獲取到的列表會是空的。另外,調用這些方法別忘了導入頭文件 #import <objc/runtime.h>。
用實例對象調用實例方法時,會到實例 isa 指針所指向的對象(即類對象)中操作;調用類方法時,則會到類對象 isa 指針所指向的對象(即元類對象)中操作。
這一過程帶來兩點啟發:
super 標識,它在運行時會跳過當前類對象的查找過程。當消息傳遞最終找不到方法時,在崩潰之前,你还有機會通過重寫 NSObject 的以下四個方法來接管:
+ (BOOL)resolveClassMethod:(SEL)sel; + (BOOL)resolveInstanceMethod:(SEL)sel; // 後兩個方法用於轉發到其他類處理 - (id)forwardingTargetForSelector:(SEL)aSelector; - (void)forwardInvocation:(NSInvocation *)anInvocation;
invokeWithTarget: 讓某個 target 觸發。在攔截方法中返回 YES 後,可以根據傳入的 SEL 動態添加一個方法。先從外部隱式調用一個不存在的方法:
// 隱式調用方法 [target performSelector:@selector(resolveAdd:) withObject:@"test"];
再在 target 內部重寫攔截方法,動態添加實現:
void runAddMethod(id self, SEL _cmd, NSString *string){ NSLog(@"add C IMP ", string); } + (BOOL)resolveInstanceMethod:(SEL)sel{ if ([NSStringFromSelector(sel) isEqualToString:@"resolveAdd:"]) { class_addMethod(self, sel, (IMP)runAddMethod, "v@:*"); } return YES; }class_addMethod 的四個參數分別是:
+ (IMP)instanceMethodForSelector: 獲取。當你想為系統類添加一個額外屬性時,常規做法是繼承,但僅為一個屬性而繼承往往顯得笨重。這時 Runtime 的關聯對象就能派上用場。
// 定義一個全局變量,用它的地址作為關聯對象的 key static char associatedObjectKey; // 設置關聯對象 objc_setAssociatedObject(target, &associatedObjectKey, @"添加的字符串屬性", OBJC_ASSOCIATION_RETAIN_NONATOMIC); // 獲取關聯對象 NSString *string = objc_getAssociatedObject(target, &associatedObjectKey); NSLog(@"AssociatedObject = %@", string);
objc_setAssociatedObject 的四個參數:
enum { OBJC_ASSOCIATION_ASSIGN = 0, OBJC_ASSOCIATION_RETAIN_NONATOMIC = 1, OBJC_ASSOCIATION_COPY_NONATOMIC = 3, OBJC_ASSOCIATION_RETAIN = 01401, OBJC_ASSOCIATION_COPY = 01403 };而 objc_getAssociatedObject 需要兩個參數:id object(獲取誰的關聯對象)與 const void *key(根據唯一 key 取值)。你還可以把添加與獲取的方法封裝進相關類的類別(Category)中,方便調用。
// 添加關聯對象 - (void)addAssociatedObject:(id)object{ objc_setAssociatedObject(self, @selector(getAssociatedObject), object, OBJC_ASSOCIATION_RETAIN_NONATOMIC); } // 獲取關聯對象 - (id)getAssociatedObject{ return objc_getAssociatedObject(self, _cmd); }注意:這裡把 getAssociatedObject 方法的地址作為唯一 key,_cmd 代表當前調用方法的地址。
方法交換顧名思義,就是把兩個方法的實現互換。交換 A、B 之後,調用 A 會執行 B 的代碼,反之亦然。以下代碼參考自 Mattt 大神在 NSHipster 上的文章:
#import "UIViewController+swizzling.h" #import @implementation UIViewController (swizzling) // load 方法會在類第一次加載時被調用,時機較早,適合做方法交換 + (void)load{ static dispatch_once_t onceToken; dispatch_once(&onceToken, ^{ SEL systemSel = @selector(viewWillAppear:); SEL swizzSel = @selector(swiz_viewWillAppear:); Method systemMethod = class_getInstanceMethod([self class], systemSel); Method swizzMethod = class_getInstanceMethod([self class], swizzSel); BOOL isAdd = class_addMethod(self, systemSel, method_getImplementation(swizzMethod), method_getTypeEncoding(swizzMethod)); if (isAdd) { class_replaceMethod(self, swizzSel, method_getImplementation(systemMethod), method_getTypeEncoding(systemMethod)); }else{ method_exchangeImplementations(systemMethod, swizzMethod); } }); } - (void)swiz_viewWillAppear:(BOOL)animated{ // 此時調用自己看似死循環,其實實現已被替換 [self swiz_viewWillAppear:animated]; NSLog(@"swizzle"); } @end在一個自定義的 viewController 中重寫 viewWillAppear:
- (void)viewWillAppear:(BOOL)animated{ [super viewWillAppear:animated]; NSLog(@"viewWillAppear"); }Run 起來看看輸出即可驗證效果。
筆者理解: