Runtime基本應(yīng)用

1、方法交換(Method-Swizzling黑魔法)

  + (void)load
{
    Method test = class_getInstanceMethod(self, @selector(test));

    Method otherTest = class_getInstanceMethod(self, @selector(otherTest));

    method_exchangeImplementations(test, otherTest);
}

應(yīng)用場(chǎng)景:替換系統(tǒng)的方法,比如viewDidLoad,viewWillAppear以及一些響應(yīng)方法,來進(jìn)行統(tǒng)計(jì)信息。
再例如更換全局UILabel默認(rèn)字體,可以通過Method Swizzling替換UILabel初始方法來修改等

因?yàn)镸ethod Swizzling的實(shí)現(xiàn)模式比較固定,所以將其抽象為一個(gè)分類,可以直接方便調(diào)用

#import <Foundation/Foundation.h>

@interface NSObject (Swizzling)

+(void)methodSwizzlingWithOriginalSelector:(SEL)originalSelector bySwizzledSelector:(SEL)swizzledSelector;
@end

#import "NSObject+Swizzling.h"
#import <objc/runtime.h>
@implementation NSObject (Swizzling)

+(void)methodSwizzlingWithOriginalSelector:(SEL)originalSelector
                        bySwizzledSelector:(SEL)swizzledSelector{

    Class class = [self class];
    Method originalMethod = class_getInstanceMethod(class, originalSelector);
    Method swizzleMethod = class_getInstanceMethod(class, swizzledSelector);

    BOOL didAddMethod = class_addMethod(class, originalSelector, method_getImplementation(swizzleMethod), method_getTypeEncoding(swizzleMethod));
    if (didAddMethod) {
        class_replaceMethod(class, swizzledSelector, method_getImplementation(originalMethod), method_getTypeEncoding(originalMethod));
    }else{
        method_exchangeImplementations(originalMethod, swizzleMethod);
    }
}
@end
  • class_addMethod:會(huì)覆蓋父類的方法實(shí)現(xiàn),但不會(huì)取代本類中已存在的實(shí)現(xiàn)。如果本類中包含一個(gè)同名的實(shí)現(xiàn),則函數(shù)返回NO。這里為源SEL添加IMP是為了避免源SEL沒有實(shí)現(xiàn)IMP的情況。若添加成功則說明源SEL沒有實(shí)現(xiàn)IMP,將源SEL的IMP替換到交換SEL的IMP;若添加失敗則說明源SEL已經(jīng)有IMP了,直接將兩個(gè)SEL的IMP交換就可以了

  • class_replaceMethod
    該函數(shù)的行為分為兩種:如果類中不存在name指定的方法,則類似于clss_addMethod函數(shù)一樣會(huì)添加方法;
    如果類中已存在name指定的方法,則類似于method_setImplementation一樣代替原方法的實(shí)現(xiàn)。

實(shí)現(xiàn)第一個(gè)場(chǎng)景:跟蹤程序每個(gè)ViewController展示給用戶的次數(shù),可以通過Method Swizzling替換ViewDidAppear初始方法。

創(chuàng)建一個(gè)UIViewController的分類,重寫自定義的ViewDidAppear方法,并在其+load方法中實(shí)現(xiàn)ViewDidAppear方法的交換。

#import <UIKit/UIKit.h>
@interface UIViewController (Swizzling)
@end

#import "UIViewController+Swizzling.h"
#import "NSObject+Swizzling.h"

@implementation UIViewController (Swizzling)
+(void)load{
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        [UIViewController methodSwizzlingWithOriginalSelector:@selector(viewDidAppear:)
                                           bySwizzledSelector:@selector(my_ViewDidAppear:)];

    });
    }
-(void) my_ViewDidAppear:(BOOL)animated{
    [self my_ViewDidAppear:animated];
    NSLog(@"===== %@ viewDidAppear=====",[self class]);
}
@end

注意:

  • Swizzling應(yīng)該總在+load中執(zhí)行。
  • 在OC中,Runtime會(huì)在類初始加載時(shí)調(diào)用+load方法,在類第一次被調(diào)用時(shí)實(shí)現(xiàn)+initialize方法。由于Method Swizzling會(huì)影響到類的全局狀態(tài),所以要盡量避免在并發(fā)處理中出現(xiàn)競(jìng)爭(zhēng)情況。+load方法能保證在類的初始化過程中被加載,并保證這種改變應(yīng)用級(jí)別的行為的一致性。
  • 要使用dispatch_once執(zhí)行方法交換
    方法交換要求線程安全,而且保證在任何情況下只能交換一次。
//例如:image 的方法交換

#import "UIImage+swizzing.h"

 @implementation UIImage (swizzing)

+ (void)load{

    NSLog(@"imae laod");

    Method oldMethod = class_getClassMethod(self, @selector(imageNamed:));

    Method newMethod = class_getClassMethod(self, @selector(sw_imageWithName:));

  method_exchangeImplementations(oldMethod, newMethod);

}

+ (UIImage *)sw_imageWithName:(NSString *)imageName{

     // 這里調(diào)用sw_imageWithName,相當(dāng)于調(diào)用imageName

    UIImage *image = [UIImage sw_imageWithName:imageName];

    if (!image) {

        NSLog(@"imgae nil");

    }

    NSLog(@"new method");

    return image;

}

@end

2、給分類增加屬性

開發(fā)中常需要在不改變某個(gè)類的前提下為其添加一個(gè)新的屬性,尤其是為系統(tǒng)的類添加新的屬性,這個(gè)時(shí)候就可以利用Runtime的關(guān)聯(lián)對(duì)象(Associated Objects)來為分類添加新的屬性了。

關(guān)聯(lián)對(duì)象是Runtime的一個(gè)特性,Runtime中定義了三個(gè)將任何鍵值在Runtime關(guān)聯(lián)到對(duì)象上的函數(shù):

  • objc_setAssociatedObject 設(shè)置關(guān)聯(lián)對(duì)象:
    void objc_setAssociatedObject(id object, const void *key, id value, objc_AssociationPolicy policy)

  • objc_getAssociatedObject 獲取關(guān)聯(lián)對(duì)象
    id objc_getAssociatedObject(id object, const void *key)

  • objc_removeAssociatedObjects移除某個(gè)對(duì)象的所有關(guān)聯(lián)對(duì)象,此方法不常用。

為UIImage類添加一個(gè)downLoadURL的屬性。

#import <UIKit/UIKit.h>

@interface UIImage (downLoadURL)
@property (nonatomic, strong) NSString *downLoadURL;
@end

#import "UIImage+downLoadURL.h"
#import <objc/runtime.h>
@implementation UIImage (downLoadURL)

-(void)setDownLoadURL:(NSString *)downLoadURL{
    objc_setAssociatedObject(self, @selector(downLoadURL), downLoadURL, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
}
-(NSString *)downLoadURL{
    return objc_getAssociatedObject(self, @selector(downLoadURL));
}
@end

有名的第三方庫(kù)LTNavigationBar在實(shí)現(xiàn)滑動(dòng)界面時(shí)導(dǎo)航欄顯隱功能時(shí)也使用了Associated Objects,為UINavigation類添加了一個(gè)UIView類的屬性overlay,使功能實(shí)現(xiàn)起來更加簡(jiǎn)便。大家可以閱讀一下源碼。

3、實(shí)現(xiàn)字典和模型的自動(dòng)轉(zhuǎn)換

優(yōu)秀的JSON轉(zhuǎn)模型第三方庫(kù)JSONModel、YYModel等都利用runtime對(duì)屬性進(jìn)行獲取,賦值等操作

閱讀YYModel的源碼可以看出,YY大神對(duì)NSObject的內(nèi)容進(jìn)行了又一次封裝,添加了許多描述內(nèi)容。其中YYClassInfo是對(duì)Class進(jìn)行了再次封裝,而YYClassIvarInfo、YYClassMethodInfo、YYClPropertyInfo分別是對(duì)Class的Ivar、Method和property進(jìn)行了封裝和描述。在提取Class的相關(guān)信息時(shí)都運(yùn)用了Runtime。

源碼中提取Class的Ivar的相關(guān)代碼:
unsigned int ivarCount = 0;
    Ivar *ivars = class_copyIvarList(cls, &ivarCount);
    if (ivars) {
        NSMutableDictionary *ivarInfos = [NSMutableDictionary new];
        _ivarInfos = ivarInfos;
        for (unsigned int i = 0; i < ivarCount; i++) {
            YYClassIvarInfo *info = [[YYClassIvarInfo alloc] initWithIvar:ivars[i]];
            if (info.name) ivarInfos[info.name] = info;
        }
        free(ivars);
    }

為了方便大家更好的理解字典轉(zhuǎn)模型,我粗略的寫了一個(gè)極簡(jiǎn)陋版的轉(zhuǎn)模型方案供大家理解其思路,更優(yōu)秀完美的思路建議大家閱讀優(yōu)秀第三方框架的源碼。

@interface NSObject (ZCModel)
+(instancetype) setModelWithDict:(NSDictionary*)dict;
@end

@implementation NSObject (ZCModel)
+(instancetype) setModelWithDict:(NSDictionary*)dict{

    Class cls = [self class];
    id Model = [[self alloc]init];

    unsigned int count;
    //提取Class的property列表
    objc_property_t *property_t = class_copyPropertyList(cls, &count);
    //遍歷列表,對(duì)每個(gè)property分別處理
    for (int i =0; i< count; i++) {
        objc_property_t property = property_t[i];
        NSString *key = [NSString stringWithUTF8String:property_getName(property)];

        id value = dict[key];
        if (!value) continue;
        //提取property的attribute信息
        NSString *attribure = [NSString stringWithUTF8String:property_getAttributes(property)];
        //從attribute信息中提取其class的信息
        if ([attribure hasPrefix:@"T@"]) {
            NSRange range =  [attribure rangeOfString:@"\","];
            NSString *typeString = [attribure substringWithRange:NSMakeRange(3, range.location  - 3)];

            NSLog(@"the property class is %@",typeString);
            //對(duì)非NS開頭的class處理為嵌套的model,對(duì)model進(jìn)行遞歸,轉(zhuǎn)為模型
            if (![typeString hasPrefix:@"NS"]) {

                Class modelClass = NSClassFromString(typeString);
                value = [modelClass setModelWithDict:value];
            }
        }
        //將字典中的值設(shè)置給模型
        [Model setValue:value forKeyPath:key];
    }

    free(property_t);
    return Model;
}
@end

4、實(shí)現(xiàn)NSCoding的自動(dòng)歸檔和自動(dòng)解檔

實(shí)現(xiàn)<NSCoding>協(xié)議

//獲取所有屬性

- (NSArray *)propertyOfSelf{

     unsigned int count = 0;

    Ivar *ivarList = class_copyIvarList([self class], &count);

    NSMutableArray *propertyArr = [NSMutableArray array];

    for (int i = 0; i<count; i++) {

        //獲取成員屬性

        Ivar ivar = ivarList[i];

        //屬性名

        NSString *name = [NSString stringWithUTF8String:ivar_getName(ivar)];

         //去掉屬性名前面的_

        NSString *key = [name substringFromIndex:1];

        [propertyArr addObject:key];

    }

     return [propertyArr copy];

}

//歸檔
- (void)encodeWithCoder:(NSCoder *)aCoder{

    NSArray *propertyNames = [self propertyOfSelf];

    for (NSString *properName in propertyNames) {

        id value = [self valueForKey:properName];//KVC

        [aCoder encodeObject:value forKey:properName];

    }
}

//解檔

- (instancetype)initWithCoder:(NSCoder *)coder
{
    self = [super init];

    if (self) {

        NSArray *propertyNames = [self propertyOfSelf];

        for (NSString *properName in propertyNames) {

            id value = [coder decodeObjectForKey:properName];

            [self setValue:value forKey:properName];//KVC

        }

   }

    return self;
}

//使用
- (IBAction)arch:(id)sender {

    Student *pp = [Student new];

    pp.name = @"xiaoming";

    pp.age = @"11";

    NSLog(@"Name:%@--%@",pp.name,pp.age);

 NSData *data = [NSKeyedArchiver archivedDataWithRootObject:pp];

    [[NSUserDefaults standardUserDefaults] setObject:data forKey:@"sss"];

}
- (IBAction)unarch:(id)sender {

 NSData *data = [[NSUserDefaults standardUserDefaults]objectForKey:@"sss"];

  Student *stu = [NSKeyedUnarchiver unarchiveObjectWithData:data];

   NSLog(@"Name:%@--%@",stu.name,stu.age);
}

5、消息轉(zhuǎn)發(fā)(熱更新)解決Bug(JSPatch)

JSPatch是個(gè)優(yōu)秀開源項(xiàng)目,在項(xiàng)目里引入極小的引擎文件就可以使用JavaScript調(diào)用任何OC的原生接口,替換任意的OC原生方法。
目前主要用于下發(fā)JS腳本替換原生OC代碼,實(shí)時(shí)修復(fù)線上bug,更多詳情可以閱讀JSPatch技術(shù)文檔。
JSPatch能做到通過JS調(diào)用和改寫OC方法最根本的原因是OC是動(dòng)態(tài)語(yǔ)言,OC上所有方法的調(diào)用和類的生成都通過OC Runtime在運(yùn)行時(shí)進(jìn)行,我們可以通過類名/方法名反射得到相應(yīng)的類和方法。
所以JSPatch的基本原理是:JS傳遞字符串給OC,OC通過Runtime接口調(diào)用和替換OC方法。
在JSPatch實(shí)現(xiàn)方法替換上,通過Selector調(diào)用方法時(shí),會(huì)從methodList鏈表里找到對(duì)應(yīng)的Method進(jìn)行調(diào)用,這個(gè)methodList上的元素是可以動(dòng)態(tài)替換的,可以把某個(gè)Selector對(duì)應(yīng)的函數(shù)指針I(yè)MP替換成新的,也可以拿到已有的某個(gè)Selector對(duì)應(yīng)的函數(shù)指針I(yè)MP,讓另一個(gè)Selector跟它對(duì)應(yīng),Runtime提供了相應(yīng)的方法實(shí)現(xiàn)這些。
現(xiàn)在蘋果審核嚴(yán)格可能使用熱更新后審核被拒

6、防止按鈕多次點(diǎn)擊runtime

參考別人簡(jiǎn)書詳細(xì)實(shí)現(xiàn)

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

友情鏈接更多精彩內(nèi)容