iOS RunTime解析

歡迎你們關注個人公衆號,我會按期分享一些我在項目中遇到問題的解決辦法和一些iOS實用的技巧,現階段主要是整理出一些基礎的知識記錄下來
javascript

文章也會同步更新到個人博客:
ppsheep.comjava

RunTime一直是iOS開發中很是重要的並且必需要理解的東西,最近在學習RunTime,有本身的一些心得,如今記錄下來,便於之後查閱git

什麼是RunTime

  • 咱們寫的代碼在程序運行過程當中都會被轉化成runtime的C代碼執行,例如[target doSomething]方法會被轉化成 objc_msgSend(target,@select(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; /* Use `Class` instead of `struct objc_class *` */複製代碼

獲取類中的屬性方法列表等

有時候咱們有這樣的需求,須要知道當前類中的每一個屬性的名字github

咱們能夠經過runtime的一系列方法獲取類的一些信息(包括屬性列表,方法列表,成員變量列表,和遵循的協議列表)swift

unsigned int count;
//獲取屬性列表
objc_property_t *propertyList = class_copyPropertyList([self class], &count); for (unsigned int i=0; i<count; i++) {
    const char *propertyName = property_getName(propertyList[i]);
    NSLog(@"property---->%@", [NSString stringWithUTF8String:propertyName]);
}

//獲取方法列表
Method *methodList = class_copyMethodList([self class], &count); for (unsigned int i; i<count; i++) {
    Method method = methodList[i];
    NSLog(@"method---->%@", NSStringFromSelector(method_getName(method)));
}

//獲取成員變量列表
Ivar *ivarList = class_copyIvarList([self class], &count); for (unsigned int i; i<count; i++) {
    Ivar myIvar = ivarList[i];
    const char *ivarName = ivar_getName(myIvar);
    NSLog(@"Ivar---->%@", [NSString stringWithUTF8String:ivarName]);
}

//獲取協議列表
__unsafe_unretained Protocol **protocolList = class_copyProtocolList([self class], &count); for (unsigned int i; i<count; i++) {
    Protocol *myProtocal = protocolList[i];
    const char *protocolName = protocol_getName(myProtocal);
    NSLog(@"protocol---->%@", [NSString stringWithUTF8String:protocolName]);
}複製代碼

咱們來測試一下 新建一個工程緩存

在.h文件中學習

#import <UIKit/UIKit.h>

@interface ViewController : UIViewController<UITabBarDelegate>

@property (nonatomic, copy) NSString *property1;
@property (nonatomic, copy) NSString *property2;
@property (nonatomic, copy) NSString *property3;
@property (nonatomic, copy) NSString *property4;

- (void)testGetMethods;

@end複製代碼

在.m文件中測試

#import "ViewController.h"
#import <objc/runtime.h>

@interface ViewController ()<UINavigationBarDelegate>
{
    @private
    NSUInteger countTest;
}

@property (nonatomic, copy) NSString *property5;
@property (nonatomic, copy) NSString *property6;
@property (nonatomic, copy) NSString *property7;
@property (nonatomic, copy) NSString *property8;

@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    [self getProperties];
}

- (void)getProperties{
    unsigned int count;
    //獲取屬性列表
    NSLog(@"----------獲取屬性---------");
    objc_property_t *propertyList = class_copyPropertyList([self class], &count); for (unsigned int i=0; i<count; i++) {
        const char *propertyName = property_getName(propertyList[i]);
        NSLog(@"property---->%@", [NSString stringWithUTF8String:propertyName]);
    }
    NSLog(@"----------獲取方法---------");
    //獲取方法列表
    Method *methodList = class_copyMethodList([self class], &count); for (unsigned int i; i<count; i++) {
        Method method = methodList[i];
        NSLog(@"method---->%@", NSStringFromSelector(method_getName(method)));
    }
    NSLog(@"----------獲取成員變量---------");
    //獲取成員變量列表
    Ivar *ivarList = class_copyIvarList([self class], &count); for (unsigned int i; i<count; i++) {
        Ivar myIvar = ivarList[i];
        const char *ivarName = ivar_getName(myIvar);
        NSLog(@"Ivar---->%@", [NSString stringWithUTF8String:ivarName]);
    }
    NSLog(@"----------獲取協議---------");
    //獲取協議列表
    __unsafe_unretained Protocol **protocolList = class_copyProtocolList([self class], &count); for (unsigned int i; i<count; i++) {
        Protocol *myProtocal = protocolList[i];
        const char *protocolName = protocol_getName(myProtocal);
        NSLog(@"protocol---->%@", [NSString stringWithUTF8String:protocolName]);
    }
}

-(void)testGetMethods{

}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];

}

@end複製代碼

運行一下 咱們看輸出優化

2016-10-31 10:34:15.698751 iOS RunTime解析[1023:187762] ----------獲取屬性---------
2016-10-31 10:34:15.698886 iOS RunTime解析[1023:187762] property---->property5
2016-10-31 10:34:15.698950 iOS RunTime解析[1023:187762] property---->property6
2016-10-31 10:34:15.698999 iOS RunTime解析[1023:187762] property---->property7
2016-10-31 10:34:15.699046 iOS RunTime解析[1023:187762] property---->property8
2016-10-31 10:34:15.699160 iOS RunTime解析[1023:187762] property---->property1
2016-10-31 10:34:15.699211 iOS RunTime解析[1023:187762] property---->property2
2016-10-31 10:34:15.699257 iOS RunTime解析[1023:187762] property---->property3
2016-10-31 10:34:15.699305 iOS RunTime解析[1023:187762] property---->property4
2016-10-31 10:34:15.699369 iOS RunTime解析[1023:187762] property---->hash
2016-10-31 10:34:15.699470 iOS RunTime解析[1023:187762] property---->superclass
2016-10-31 10:34:15.699520 iOS RunTime解析[1023:187762] property---->description
2016-10-31 10:34:15.699804 iOS RunTime解析[1023:187762] property---->debugDescription
2016-10-31 10:34:15.699872 iOS RunTime解析[1023:187762] ----------獲取方法---------
2016-10-31 10:34:15.699970 iOS RunTime解析[1023:187762] method---->getProperties
2016-10-31 10:34:15.700054 iOS RunTime解析[1023:187762] method---->testGetMethods
2016-10-31 10:34:15.700124 iOS RunTime解析[1023:187762] method---->property1
2016-10-31 10:34:15.700188 iOS RunTime解析[1023:187762] method---->setProperty1:
2016-10-31 10:34:15.700249 iOS RunTime解析[1023:187762] method---->property2
2016-10-31 10:34:15.700399 iOS RunTime解析[1023:187762] method---->setProperty2:
2016-10-31 10:34:15.700485 iOS RunTime解析[1023:187762] method---->property3
2016-10-31 10:34:15.700596 iOS RunTime解析[1023:187762] method---->setProperty3:
2016-10-31 10:34:15.700666 iOS RunTime解析[1023:187762] method---->property4
2016-10-31 10:34:15.700789 iOS RunTime解析[1023:187762] method---->setProperty4:
2016-10-31 10:34:15.700885 iOS RunTime解析[1023:187762] method---->property5
2016-10-31 10:34:15.700937 iOS RunTime解析[1023:187762] method---->setProperty5:
2016-10-31 10:34:15.700988 iOS RunTime解析[1023:187762] method---->property6
2016-10-31 10:34:15.701036 iOS RunTime解析[1023:187762] method---->setProperty6:
2016-10-31 10:34:15.701083 iOS RunTime解析[1023:187762] method---->property7
2016-10-31 10:34:15.701132 iOS RunTime解析[1023:187762] method---->setProperty7:
2016-10-31 10:34:15.701244 iOS RunTime解析[1023:187762] method---->property8
2016-10-31 10:34:15.701309 iOS RunTime解析[1023:187762] method---->setProperty8:
2016-10-31 10:34:15.701440 iOS RunTime解析[1023:187762] method---->.cxx_destruct
2016-10-31 10:34:15.701518 iOS RunTime解析[1023:187762] method---->didReceiveMemoryWarning
2016-10-31 10:34:15.701621 iOS RunTime解析[1023:187762] method---->viewDidLoad
2016-10-31 10:34:15.701671 iOS RunTime解析[1023:187762] ----------獲取成員變量---------
2016-10-31 10:34:15.701746 iOS RunTime解析[1023:187762] Ivar---->countTest
2016-10-31 10:34:15.701795 iOS RunTime解析[1023:187762] Ivar---->_property1
2016-10-31 10:34:15.701865 iOS RunTime解析[1023:187762] Ivar---->_property2
2016-10-31 10:34:15.701916 iOS RunTime解析[1023:187762] Ivar---->_property3
2016-10-31 10:34:15.701964 iOS RunTime解析[1023:187762] Ivar---->_property4
2016-10-31 10:34:15.702012 iOS RunTime解析[1023:187762] Ivar---->_property5
2016-10-31 10:34:15.702059 iOS RunTime解析[1023:187762] Ivar---->_property6
2016-10-31 10:34:15.702106 iOS RunTime解析[1023:187762] Ivar---->_property7
2016-10-31 10:34:15.702154 iOS RunTime解析[1023:187762] Ivar---->_property8
2016-10-31 10:34:15.702192 iOS RunTime解析[1023:187762] ----------獲取協議---------
2016-10-31 10:34:15.702850 iOS RunTime解析[1023:187762] protocol---->UINavigationBarDelegate
2016-10-31 10:34:15.702908 iOS RunTime解析[1023:187762] protocol---->UITabBarDelegate複製代碼

咱們能夠看到 不管是.h中申明 仍是.m中的申明 所有打印了出來ui

並且還有一個規律 就是.m中的屬性和方法 老是被首先打印出來

方法調用

咱們看一下方法調用在運行時的過程

若是用實例對象調用實例方法,會到實例的isa指針指向的對象(也就是類對象)操做。

若是調用的是類方法,就會到類對象的isa指針指向的對象(也就是元類對象)中操做。

  • 首先,在相應操做的對象中的緩存方法列表中找調用的方法,若是找到,轉向相應實現並執行。
  • 若是沒找到,在相應操做的對象中的方法列表中找調用的方法,若是找到,轉向相應實現執行
  • 若是沒找到,去父類指針所指向的對象中執行1,2.
  • 以此類推,若是一直到根類還沒找到,轉向攔截調用。
  • 若是沒有重寫攔截調用的方法,程序報錯。

那麼 這樣 咱們是否是能夠這樣作呢?

  • 重寫父類的方法,並無覆蓋掉父類的方法,只是在當前類對象中找到了這個方法後就不會再去父類中找了。
  • 若是想調用已經重寫過的方法的父類的實現,只需使用super這個編譯器標識,它會在運行時跳過在當前的類對象中尋找方法的過程。

攔截調用

在方法調用中說到了,若是沒有找到方法就會轉向攔截調用。

那麼什麼是攔截調用呢。

攔截調用就是,在找不到調用的方法程序崩潰以前,你有機會經過重寫NSObject的四個方法來處理。

+ (BOOL)resolveClassMethod:(SEL)sel;
+ (BOOL)resolveInstanceMethod:(SEL)sel;
//後兩個方法須要轉發到其餘的類處理
- (id)forwardingTargetForSelector:(SEL)aSelector;
- (void)forwardInvocation:(NSInvocation *)anInvocation;複製代碼
  • 第一個方法是當你調用一個不存在的類方法的時候,會調用這個方法,默認返回NO,你能夠加上本身的處理而後返回YES。
  • 第二個方法和第一個方法類似,只不過處理的是實例方法。
  • 第三個方法是將你調用的不存在的方法重定向到一個其餘聲明瞭這個方法的類,只須要你返回一個有這個方法的target。
  • 第四個方法是將你調用的不存在的方法打包成NSInvocation傳給你。作完你本身的處理後,調用invokeWithTarget:方法讓某個target觸發這個方法。

動態添加方法

重寫了攔截調用的方法而且返回了YES,咱們要怎麼處理呢?
有一個辦法是根據傳進來的SEL類型的selector動態添加一個方法。

首先從外部隱式調用一個不存在的方法:

//隱式調用方法
[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的四個參數分別是:

  • Class cls 給哪一個類添加方法,本例中是self
  • SEL name 添加的方法,本例中是重寫的攔截調用傳進來的selector。
  • IMP imp 方法的實現,C方法的方法實現能夠直接得到。若是是OC方法,能夠用+ (IMP)instanceMethodForSelector:(SEL)aSelector;得到方法的實現。
  • 「v@:*」方法的簽名,表明有一個參數的方法。

關聯對象

如今你準備用一個系統的類,可是系統的類並不能知足你的需求,你須要額外添加一個屬性。
這種狀況的通常解決辦法就是繼承。

可是,只增長一個屬性,就去繼承一個類,老是以爲太麻煩類。

這個時候,runtime的關聯屬性就發揮它的做用了。

//首先定義一個全局變量,用它的地址做爲關聯對象的key
static char associatedObjectKey;
//設置關聯對象
objc_setAssociatedObject(target, &associatedObjectKey, @"添加的字符串屬性", OBJC_ASSOCIATION_RETAIN_NONATOMIC); 
//獲取關聯對象
NSString *string = objc_getAssociatedObject(target, &associatedObjectKey);
NSLog(@"AssociatedObject = %@", string);複製代碼

objc_setAssociatedObject的四個參數:

  • id object給誰設置關聯對象。
  • const void *key關聯對象惟一的key,獲取時會用到。
  • id value關聯對象。
  • objc_AssociationPolicy關聯策略,有如下幾種策略:
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獲取關聯對象。

其實,你還能夠把添加和獲取關聯對象的方法寫在你須要用到這個功能的類的類別中,方便使用。

//添加關聯對象
- (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方法中的代碼,反之亦然。

咱們來試一下 定義一個UIViewController的category

/** load方法會在類第一次加載的時候被調用 調用的時間比較靠前,適合在這個方法裏作方法交換 */
+(void)load{
    //方法交換應該被保證,在程序中只會執行一次
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        //得到viewController的生命週期方法的selector
        SEL systemSel = @selector(viewWillAppear:);
        //本身實現的將要被交換的方法的selector
        SEL customeSel = @selector(custome_viewWillAppear:);
        //兩個方法的Method
        Method systemMethod = class_getInstanceMethod([self class], systemSel); Method customeMethod = class_getInstanceMethod([self class], customeSel); //首先動態添加方法,實現是被交換的方法,返回值表示添加成功仍是失敗 BOOL isAdd = class_addMethod(self, systemSel, method_getImplementation(customeMethod), method_getTypeEncoding(customeMethod)); if (isAdd) {
            //若是成功,說明類中不存在這個方法的實現
            //將被交換方法的實現替換到這個並不存在的實現
            class_replaceMethod(self, customeSel, method_getImplementation(systemMethod), method_getTypeEncoding(systemMethod));
        }else{
            //不然,交換兩個方法的實現
            method_exchangeImplementations(systemMethod, customeMethod);
        }

    });
}

- (void)custome_viewWillAppear:(BOOL)animated{
    //這時候調用本身,看起來像是死循環
    //可是其實本身的實現已經被替換了
    [self custome_viewWillAppear:animated];//這裏 是去執行系統的viewWillApper:方法
    NSLog(@"custome");
}複製代碼

在其餘的controller中

#import <UIKit/UIKit.h>
#import "UIViewController+Custome.h"

@interface ViewController : UIViewController<UITabBarDelegate>

@property (nonatomic, copy) NSString *property1;
@property (nonatomic, copy) NSString *property2;
@property (nonatomic, copy) NSString *property3;
@property (nonatomic, copy) NSString *property4;

- (void)testGetMethods;

@end複製代碼

在.m中咱們重寫vieWillApper:方法

-(void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
}複製代碼

咱們將會看到在控制檯 直接打印出了custome

其實vieWillApper:方法已經被咱們替換成咱們本身的custome_viewWillAppear:

而後在咱們自定義的custome_viewWillAppear:方法中 又調用了custome_viewWillAppear:自己 其實他已經被替換成viewWillApper:方法 因此這樣就實現了 方法交換

寫的有點多了

演示代碼 我放在了

github.com/yangqian111…

大功告成

相關文章
相關標籤/搜索