iOS-底层原理(18)-runtime-之API详解+项目实践

序言

本篇文章主要介绍runtime有关API及使用

一 类

1.1 动态创建一个类(参数:父类,类名,额外的内存空间)

Class objc_allocateClassPair(Class superclass, const char *name, size_t extraBytes)

1.2 注册一个类(要在类注册之前添加成员变量)

void objc_registerClassPair(Class cls)

1.3 销毁一个类

void objc_disposeClassPair(Class cls)

  • 以上三个方法使用下面例子做讲解
// 建一个命令行工程
#import 
#import 

void run(id self, SEL _cmd) {
    NSLog(@"_____ %@ - %@", self, NSStringFromSelector(_cmd));
}

int main(int argc, const char * argv[]) {
    @autoreleasepool {
        // insert code here...
        // 动态创建一个类
        Class newClass = objc_allocateClassPair([NSObject class], "CSDog", 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];
        [dog setValue:@10 forKey:@"_age"];
        [dog setValue:@20 forKey:@"_weight"];
        [dog run];

        NSLog(@"%@ %@", [dog valueForKey:@"_age"], [dog valueForKey:@"_weight"]);

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

运行结果

image.png
1.4 获取isa指向的Class

Class object_getClass(id obj)

1.5 设置isa指向的Class

Class object_setClass(id obj, Class cls)

1.6 判断一个OC对象是否为Class

BOOL object_isClass(id obj)

  • 上面三个方法以下面代码做例子
@interface CSPersion : NSObject
- (void)run;
@end

@implementation CSPersion
- (void)run {
    NSLog(@"%s", __func__);
}
@end
@interface CSCar : NSObject
- (void)run;
@end

@implementation CSCar
- (void)run {
    NSLog(@"%s", __func__);
}
@end
int main(int argc, const char * argv[]) {
    @autoreleasepool {
        // insert code here...
        
        CSPersion *persion = [[CSPersion alloc] init];
        [persion run];
        
        object_setClass(persion, [CSCar class]);
        [persion run];
        
        object_getClass([CSPersion class]);
        
        NSLog(@"%p %p", object_getClass([CSPersion class]), [CSPersion class]);
        
        NSLog(@"%d %d %d",
              object_isClass(persion),
              object_isClass([CSPersion class]),
              object_isClass(object_getClass([CSPersion class]))
              );
    }
    return 0;
}

运行结果如下


iOS-底层原理(18)-runtime-之API详解+项目实践_第1张图片
getClass.png
1.7 判断一个Class是否为元类

BOOL class_isMetaClass(Class cls)

1.8 获取父类

Class class_getSuperclass(Class cls)

二 成员变量

公共使用类

@interface CSPersion : NSObject
@property (assign, nonatomic) int ID;
@property (assign, nonatomic) int weight;
@property (assign, nonatomic) int age;
@property (copy, nonatomic) NSString *name;
- (void)run;
@end
2.1 获取一个实例变量信息
  • Ivar class_getInstanceVariable(Class cls, const char *name)
2.2 获取成员变量的相关信息
  • const char *ivar_getName(Ivar v)
  • const char *ivar_getTypeEncoding(Ivar v)

2.1,2.2使用如下代码做例子

int main(int argc, const char * argv[]) {
    @autoreleasepool {
        // insert code here...
        
        // 1.获取成员变量信息
        Ivar ageIvar = class_getInstanceVariable([CSPersion class], "_age");
        NSLog(@"%s %s",ivar_getName(ageIvar),ivar_getTypeEncoding(ageIvar));
    }
    return 0;
}

运行结果

ivar.png
2.3 设置和获取成员变量的值
  • void object_setIvar(id obj, Ivar ivar, id value)
  • id object_getIvar(id obj, Ivar ivar)

代码例子如下

int main(int argc, const char * argv[]) {
    @autoreleasepool { 
        // 2. 设置和获取成员变量的值
        CSPersion *persion = [[CSPersion alloc] init];
        Ivar nameIvar = class_getInstanceVariable([CSPersion class], "_name");
        Ivar ageIvar = class_getInstanceVariable([CSPersion class], "_age");
        
        object_setIvar(persion, nameIvar, @"123");
        object_setIvar(persion, ageIvar, (__bridge id)(void *)10);
        NSLog(@"%@ %d", persion.name, persion.age);
    }
    return 0;
}

运行结果如下

setIvar.png
2.4 动态添加成员变量(已经注册的类是不能动态添加成员变量的)
  • BOOL class_addIvar(Class cls, const char * name, size_t size, uint8_t alignment, const char * types)
int main(int argc, const char * argv[]) {
    @autoreleasepool {
        // 动态创建一个类
        Class newClass = objc_allocateClassPair([NSObject class], "CSDog", 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];
        [dog setValue:@10 forKey:@"_age"];
        [dog setValue:@20 forKey:@"_weight"];
        [dog run];

        NSLog(@"%@ %@", [dog valueForKey:@"_age"], [dog valueForKey:@"_weight"]);
        
        // 在不需要这个类时释放
        objc_disposeClassPair(newClass);
    }
    return 0;
}

运行结果如下

class_addIvar.png
2.5 拷贝实例变量列表(最后需要调用free释放)
  • Ivar *class_copyIvarList(Class cls, unsigned int *outCount)
int main(int argc, const char * argv[]) {
    @autoreleasepool {
        // 4.成员变量的数量
        unsigned int count;
        Ivar *ivars = class_copyIvarList([CSPersion 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);
    }
    return 0;
}

运行结果如下

iOS-底层原理(18)-runtime-之API详解+项目实践_第2张图片
class_copyIvarList.png
三 属性
3.1 获取一个属性
  • objc_property_t class_getProperty(Class cls, const char *name)
3.2 拷贝属性列表(最后需要调用free释放)
  • objc_property_t *class_copyPropertyList(Class cls, unsigned int *outCount)
3.3 动态添加属性
  • BOOL class_addProperty(Class cls, const char *name, const objc_property_attribute_t *attributes, unsigned int attributeCount)
3.4 动态替换属性
  • void class_replaceProperty(Class cls, const char *name, const objc_property_attribute_t *attributes, unsigned int attributeCount)
3.5 获取属性的一些信息
  • const char *property_getName(objc_property_t property)
  • const char *property_getAttributes(objc_property_t property)
四 方法
4.1 获得一个实例方法、类方法
  • Method class_getInstanceMethod(Class cls, SEL name)
  • Method class_getClassMethod(Class cls, SEL name)
4.2 方法实现相关操作
  • IMP class_getMethodImplementation(Class cls, SEL name)
  • IMP method_setImplementation(Method m, IMP imp)
  • void method_exchangeImplementations(Method m1, Method m2)
4.3 拷贝方法列表(最后需要调用free释放)
  • Method *class_copyMethodList(Class cls, unsigned int *outCount)
4.4 动态添加方法
  • BOOL class_addMethod(Class cls, SEL name, IMP imp, const char *types)
4.5 动态替换方法
  • IMP class_replaceMethod(Class cls, SEL name, IMP imp, const char *types)
4.6 获取方法的相关信息(带有copy的需要调用free去释放)
  • 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)
4.7 选择器相关
  • const char *sel_getName(SEL sel)
  • SEL sel_registerName(const char *str)
4.8 用block作为方法实现
  • IMP imp_implementationWithBlock(id block)
  • id imp_getBlock(IMP anImp)
  • BOOL imp_removeBlock(IMP anImp)
五 实践
5.1 交换方法实现 method_exchangeImplementations

如果需要监听所有按钮的点击事件

NS_CLASS_AVAILABLE_IOS(2_0) @interface UIButton : UIControl 

- (void)addTarget:(nullable id)target action:(SEL)action forControlEvents:(UIControlEvents)controlEvents;

- (void)sendAction:(SEL)action to:(nullable id)target forEvent:(nullable UIEvent *)event;

UIButton继承自UIControl,并且添加点击事件方法addTarget:action:forControlEvents最终是调用sendAction:to:forEvent方法,所以交换该方法即可。

1.定义UIControl的类扩展

#import "UIControl+Extension.h"
#import 

@implementation UIControl (Extension)

+ (void)load {
    // hork:钩子函数
    Method method1 = class_getInstanceMethod(self, @selector(sendAction:to:forEvent:));
    Method method2 = class_getInstanceMethod(self, @selector(cs_sendAction:to:forEvent:));
    method_exchangeImplementations(method1, method2);
}

- (void)cs_sendAction:(SEL)action to:(id)target forEvent:(UIEvent *)event {
    NSLog(@"%@-%@-%@", self, target, NSStringFromSelector(action));
    
    // 调用系统原理的实现
    [self cs_sendAction:action to:target forEvent:event];
    
    if ([self isKindOfClass:[UIButton class]]) {
        NSLog(@"拦截了所有按钮的事件");
    }
}

@end

运行结果

image.png
5.2 防止数组插入空值

我们知道如果直接给数组插入空值会崩溃

NSString *obj = nil;

NSMutableArray *array = [NSMutableArray array];
[array addObject:@"jack"];
[array insertObject:obj atIndex:0];

NSLog(@"%@", array);

运行结果

iOS-底层原理(18)-runtime-之API详解+项目实践_第3张图片
image.png

如何可以避免类似崩溃发生?

交换数组方法的实现

#import "NSMutableArray+Extension.h"
#import 

@implementation NSMutableArray (Extension)

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

- (void)cs_insertObject:(id)anObject atIndex:(NSUInteger)index {
    if (anObject == nil) {
        return;
    }
    
    [self cs_insertObject:anObject atIndex:index];
}

@end

运行结果


iOS-底层原理(18)-runtime-之API详解+项目实践_第4张图片
image.png

结果正常运行,不会发生崩溃

5.3 防止字典中key为空

1.如果往一个可变字典中插入一个键值对,并且key为空,则会发生崩溃

NSString *obj = nil;

NSMutableDictionary *dict = [NSMutableDictionary dictionary];
dict[@"name"] = @"jack";
dict[obj] = @"rose";
dict[@"age"] = obj;

NSLog(@"%@", dict);

运行结果

iOS-底层原理(18)-runtime-之API详解+项目实践_第5张图片
image.png

如果避免类似事情发生?

NSMutableDictionary添加类扩展,并交换方法实现

#import "NSMutableDictionary+Extension.h"
#import 

@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(cs_setObject:forKeyedSubscript:));
        method_exchangeImplementations(method1, method2);

        Class cls2 = NSClassFromString(@"__NSDictionaryI");
        Method method3 = class_getInstanceMethod(cls2, @selector(objectForKeyedSubscript:));
        Method method4 = class_getInstanceMethod(cls2, @selector(cs_objectForKeyedSubscript:));
        method_exchangeImplementations(method3, method4);
    });
}

- (void)cs_setObject:(id)obj forKeyedSubscript:(id)key {
    if (!key) {
        return;
    }

    [self cs_setObject:obj forKeyedSubscript:key];
}

- (id)cs_objectForKeyedSubscript:(id)key {
    if (!key) {
        return nil;
    }

    return [self cs_objectForKeyedSubscript:key];
}

@end

运行结果

image.png

正常运行,不会发生崩溃


本文主要参考MJ老师的课件,非常感谢MJ老师,并且自己附带相应的例子。

项目连接地址-runtime_API
项目连接地址-runtime_exchangeMethod


更多有关runtime文章请看下面
iOS - runtime -详解
iOS Runtime原理及使用
iOS - runtime如何通过selector找到对应的 IMP地址(分别考虑类方法和实例方法)
iOS - Runtime之面试题详解一
iOS-runtime之面试题详解二
iOS runtime的使用场景-实战篇

你可能感兴趣的:(iOS-底层原理(18)-runtime-之API详解+项目实践)