iOS 底层 - runtime的应用

2020-04-04  本文已影响0人  水中的蓝天

本文源自本人的学习记录整理与理解,其中参考阅读了部分优秀的博客和书籍,尽量以通俗简单的语句转述。引用到的地方如有遗漏或未能一一列举原文出处还望见谅与指出,另文章内容如有不妥之处还望指教,万分感谢 !

runtime在开发中的应用涉及到:类、成员变量、属性、方法相关的API

类相关API:

Class objc_allocateClassPair(Class superclass, const char *name, size_t extraBytes)
void objc_registerClassPair(Class cls)
void objc_disposeClassPair(Class cls)
Class object_getClass(id obj)
Class object_setClass(id obj, Class cls)
BOOL object_isClass(id obj)
BOOL class_isMetaClass(Class cls)
Class class_getSuperclass(Class cls)

成员变量相关API

Ivar class_getInstanceVariable(Class cls, const char *name)

应用

获取成员变量信息
Ivar ageIvar = class_getInstanceVariable([XYHPerson class], "_age");
NSLog(@"%s %s", ivar_getName(ageIvar), ivar_getTypeEncoding(ageIvar));

输出: _age i 

Ivar *class_copyIvarList(Class cls, unsigned int *outCount)

应用:
 // 成员变量的数量
    unsigned int count;
//Ivar数组
    Ivar *ivars = class_copyIvarList([XYHPerson class], &count);
    for (int i = 0; i < count; i++) {
      // 取出i位置的成员变量
       Ivar ivar = ivars[i];
      NSLog(@"%s %s", ivar_getName(ivar), ivar_getTypeEncoding(ivar));
    }
    free(ivars);释放
id obj : 给那个对象设置成员变量值或取值
Ivar ivar :成员变量
id value:需要赋的值
void object_setIvar(id obj, Ivar ivar, id value) 赋值
id object_getIvar(id obj, Ivar ivar) 取值

应用

  //获取成员变量信息
     Ivar ageIvar = class_getInstanceVariable([XYHPerson class], "_age");
     Ivar nameIvar = class_getInstanceVariable([XYHPerson class], "_name");
    
     XYHPerson *person = [[XYHPerson alloc] init];
    
     //设置和获取成员变量的值
     object_setIvar(person, nameIvar, @"123");
     //int类型的赋值需要转换
     object_setIvar(person, ageIvar, (__bridge id)(void *)10);
    
     NSLog(@"%@ %d", person.name, person.age);
    
Class cls  :给那个类添加成员变量
const char * name :变量名
size_t size               :占多少字节的空间  
uint8_t alignment   :内存对齐, 一般写1就行
const char * types :encode编码
BOOL class_addIvar(Class cls, const char * name, size_t size, uint8_t alignment, const char * types)
const char *ivar_getName(Ivar v) 变量名
const char *ivar_getTypeEncoding(Ivar v) 变量的TypeEncoding

属性相关API

objc_property_t class_getProperty(Class cls, const char *name)
objc_property_t *class_copyPropertyList(Class cls, unsigned int *outCount)
BOOL class_addProperty(Class cls, const char *name, const objc_property_attribute_t *attributes,
                  unsigned int attributeCount)
void class_replaceProperty(Class cls, const char *name, const objc_property_attribute_t *attributes,
                      unsigned int attributeCount)
const char *property_getName(objc_property_t property)
const char *property_getAttributes(objc_property_t property)

方法相关API

Method class_getInstanceMethod(Class cls, SEL name)
Method class_getClassMethod(Class cls, SEL name)
//获取某个类的某个方法实现
IMP class_getMethodImplementation(Class cls, SEL name) 

//设置某个类的某个方法实现
IMP method_setImplementation(Method m, IMP imp)

//交换两个方法的实现 
void method_exchangeImplementations(Method m1, Method m2)

应用
(这只是示例,一般不要直接在+load方法中写,且要记得使用dispatch_once函数避免多次执行方法交换)
+ (void)load{

// 1. hook:钩子函数 (把自带的函数给钩出来,换成自己的实现)
Method method1 = class_getInstanceMethod(self, @selector(sendAction:to:forEvent:));
Method method2 = class_getInstanceMethod(self, @selector(xyh_sendAction:to:forEvent:));
//2. 交换方法实现,本质就是让SEL的IMP指针指向另一个方法的实现
method_exchangeImplementations(method1, method2);
}
//3. 实现自定义方法
- (void)xyh_sendAction:(SEL)action to:(id)target forEvent:(UIEvent *)event {
    @try {
      // 4. 调用系统原来的实现
     [self xyh_sendAction:action to:target forEvent:event];
     //接下来就可以在这里加入自己的实现;
     
    }
    @catch (NSException *exception) {
         //异常处理代码
    }
    @finally {
        //回收资源
    }
}

解释:
@try
{
    // 业务逻辑
}
@catch (异常类型名1 ex)
{
    //异常处理代码
}
@catch (异常类型名2 ex)
{
    //异常处理代码
}
// 可以捕捉 N 个 异常 ...
@finally
{
//回收资源
}
Method *class_copyMethodList(Class cls, unsigned int *outCount)
BOOL class_addMethod(Class cls, SEL name, IMP imp, const char *types)
IMP class_replaceMethod(Class cls, SEL name, IMP imp, const char *types)
注意:`class_replaceMethod`内部会尝试执行`class_addMethod`和`method_exchangeImplementations`
应用
//把run方法的实现替换成block中的实现
class_replaceMethod([XYHPerson class], @selector(run), imp_implementationWithBlock(^{
        NSLog(@"123123");
    }), "v");

SEL method_getName(Method m)
IMP method_getImplementation(Method m)
const char *method_getTypeEncoding(Method m)
unsigned int method_getNumberOfArguments(Method m)
char *method_copyReturnType(Method m)
char *method_copyArgumentType(Method m, unsigned int index)
const char *sel_getName(SEL sel)
SEL sel_registerName(const char *str)
IMP imp_implementationWithBlock(id block) //把block包装成IMP方法实现
id imp_getBlock(IMP anImp)
BOOL imp_removeBlock(IMP anImp)

动态创建类、添加成员变量、方法应用

// 创建类
    Class newClass = objc_allocateClassPair([NSObject class], "MJDog", 0);
    
    //添加成员变量
    class_addIvar(newClass, "_age", 4, 1, @encode(int));
    class_addIvar(newClass, "_weight", 4, 1, @encode(int));
    
    //添加方法
    class_addMethod(newClass, @selector(run), (IMP)run, "v@:");
    
    // 注册类
    objc_registerClassPair(newClass);
    
    //初始化
    id dog = [[newClass alloc] init];
    
    //KVC 赋值
    [dog setValue:@10 forKey:@"_age"];
    [dog setValue:@20 forKey:@"_weight"];
    
    [dog run];
    
    NSLog(@"%@ %@", [dog valueForKey:@"_age"], [dog valueForKey:@"_weight"]);

    // 在不需要这个类时释放
    objc_disposeClassPair(newClass);

单层字典转模型 简单逻辑

+ (instancetype)xyh_objectWithJson:(NSDictionary *)json
{
    id obj = [[self alloc] init];
    
    unsigned int count;
    Ivar *ivars = class_copyIvarList(self, &count);
    for (int i = 0; i < count; i++) {
        // 取出i位置的成员变量
        Ivar ivar = ivars[i];
        NSMutableString *name = [NSMutableString stringWithUTF8String:ivar_getName(ivar)];
        //去掉下划线
        [name deleteCharactersInRange:NSMakeRange(0, 1)];
        
        // 设值
        id value = json[name];
        if ([name isEqualToString:@"ID"]) {
            value = json[@"id"];
        }
        [obj setValue:value forKey:name];
    }
    free(ivars);
    
    return obj;
}

过滤空值,防止把空值添加到数组或字典中

数组过滤
@implementation NSMutableArray (Extension)

+ (void)load
{
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        // 类簇:NSString、NSArray、NSDictionary,这些类的真实类型是其他类型
       //NSMutableArray的真实类型是__NSArrayM
        Class cls = NSClassFromString(@"__NSArrayM");
        Method method1 = class_getInstanceMethod(cls, @selector(insertObject:atIndex:));
        Method method2 = class_getInstanceMethod(cls, @selector(xyh_insertObject:atIndex:));
        method_exchangeImplementations(method1, method2);
    });
}

- (void)xyh_insertObject:(id)anObject atIndex:(NSUInteger)index
{
    if (anObject == nil) return;//空值就返回,不去添加
    
    [self mj_insertObject:anObject atIndex:index];
}

@end

字典过滤
要考虑可变和不可变两种情况,注意类型
因为类簇真实类型不是固定的,这种情况类型最好写成最终的父类
#import "NSMutableDictionary+Extension.h"
#import <objc/runtime.h>

@implementation NSMutableDictionary (Extension)

+ (void)load
{
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{

        Class cls = NSClassFromString(@"__NSDictionaryM");
        Method method1 = class_getInstanceMethod(cls, @selector(setObject:forKeyedSubscript:));
        Method method2 = class_getInstanceMethod(cls, @selector(xyh_setObject:forKeyedSubscript:));
        method_exchangeImplementations(method1, method2);
        
        Class cls2 = NSClassFromString(@"__NSDictionaryI");
        Method method3 = class_getInstanceMethod(cls2, @selector(objectForKeyedSubscript:));
        Method method4 = class_getInstanceMethod(cls2, @selector(xyh_objectForKeyedSubscript:));
        method_exchangeImplementations(method3, method4);

    });
}
//设值
- (void)xyh_setObject:(id)obj forKeyedSubscript:(id<NSCopying>)key
{
    if (!key) return;
    
    [self xyh_setObject:obj forKeyedSubscript:key];
}
//取值
- (id)xyh_objectForKeyedSubscript:(id)key
{
    if (!key) return nil;
    
    return [self xyh_objectForKeyedSubscript:key];
}

@end

上一篇 下一篇

猜你喜欢

热点阅读