美文网首页iOS底层原理整理
iOS runtime(4)-runtimeAPI详解和方法替换

iOS runtime(4)-runtimeAPI详解和方法替换

作者: 周灬 | 来源:发表于2019-07-19 11:50 被阅读0次

对于runtime我们前边介绍了消息机制,我们并没有介绍runtime的API.

1.runtime的API

一. runtime关于类的API

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

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

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

void objc_registerClassPair(Class cls)

③. 销毁一个类

void objc_disposeClassPair(Class cls)

例:

// 建一个命令行工程
#import <Foundation/Foundation.h>
#import <objc/runtime.h>

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;
}

注意:运用runtime动态创建一个类,注意一下需要在动态添加属性之后再注册类.(已经注册的类不能动态添加属性)

④. 获取isa指向的Class

Class object_getClass(id obj)

⑤. 设置isa指向的Class

Class object_setClass(id obj, Class cls)

⑥. 判断一个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;
}

⑦. 判断一个Class是否为元类

BOOL class_isMetaClass(Class cls)

⑧. 获取父类

Class class_getSuperclass(Class cls)

2. runtime关于成员变量的API

①. 获取一个实例变量信息

Ivar class_getInstanceVariable(Class cls, const char *name)

②. 获取成员变量的相关信息

const char *ivar_getName(Ivar v)
const char *ivar_getTypeEncoding(Ivar v)

例:

@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

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;
}

③. 设置和获取成员变量的值

void object_setIvar(id obj, Ivar ivar, id value)
id object_getIvar(id obj, Ivar ivar)

例:

@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

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;
}

④. 动态添加成员变量(已经注册的类是不能动态添加成员变量的)

BOOL class_addIvar(Class cls, const char * name, size_t size, uint8_t alignment, 
const char * types)

例:

@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

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;
}

⑤. 拷贝实例变量列表(最后需要调用free释放)

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

例:

@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

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;
}

实际应用:
A. 修改textfield的占位字的属性
a.运用runtime获取成员变量的方法:

for (int i = 0; i < count; i++) {
            // 取出i位置的成员变量
            Ivar ivar = ivars[I];
            NSLog(@"%s %s", ivar_getName(ivar), ivar_getTypeEncoding(ivar));
        }

b.然后再次修改

self.textField.placeholder = @"请输入用户名";
[self.textField setValue:[UIColor redColor] forKeyPath:@"_placeholderLabel.textColor"];

B. 字典转换成模型
a.利用Runtime遍历所有的属性或者成员变量
b.利用KVC设值

字典转换成模型代码.png

3. runtime关于属性的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)

③. 拷贝方法列表(最后需要调用free释放)

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)

⑥. 获取方法的相关信息(带有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)

⑦. 选择器相关

const char *sel_getName(SEL sel)
SEL sel_registerName(const char *str)

⑧. 用block作为方法实现

IMP imp_implementationWithBlock(id block)
id imp_getBlock(IMP anImp)
BOOL imp_removeBlock(IMP anImp)

4. 方法替换

一般我们方法交换实现都是用的method_exchangeImplementations实现的.

一. 按钮的点击交换方法

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

NS_CLASS_AVAILABLE_IOS(2_0) @interface UIButton : UIControl <NSCoding>
- (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方法,所以交换该方法即可。

实际实现代码:(UIControl的类扩展)

#import "UIControl+Extension.h"
#import <objc/runtime.h>

@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
二. 防止数组插入nil值,引起崩溃.

下边的代码如果在运行的过程中就会引起崩溃.

NSString *obj = nil;

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

NSLog(@"%@", array);

使用交换方法实现防止数组插入nil引起的崩溃

#import "NSMutableArray+Extension.h"
#import <objc/runtime.h>

@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
三. 防止字典中的key=nil值,引起崩溃.
NSString *obj = nil;

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

NSLog(@"%@", dict);

如果上边的程序运行就会发生崩溃.

#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(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<NSCopying>)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
                            想了解更多iOS学习知识请联系:QQ(814299221)

相关文章

网友评论

    本文标题:iOS runtime(4)-runtimeAPI详解和方法替换

    本文链接:https://www.haomeiwen.com/subject/kcrjlctx.html