浅谈系列-Runtime简述以及Runtime API 到底能干嘛

288 阅读6分钟

导语:通过对OC消息机制的了解,其实我们已经知道消息机制的运转就在Runtime运行时完成的。今天我们就简单的探讨一下运行时能给我们带来什么。

概念

  • OC是一门动态性非常高的语言,它允许很多的操作在运行期动态的完成,而不是全部提前编译好。

  • Runtime是一套C语言的API,封装了很多动态性相关的函数,OC的动态性就是由Runtime来支撑和实现的

我们编写的OC代码,底层都是转换成了Runtime API进行调用,同时也可以在Runtime动态的添加方法,交换方法,创建对象,遍历私有成员变量等等各种操作。

消息机制

  • 在OC中所有的方法调用都是通过Runtime的objc_msgSend函数完成的。objc_msgSend内部会进行发送消息,动态方法解析,消息转发三大步骤来确保方法的调用成功。这就是消息机制。详情请看 浅谈系列-OC消息机制是如何运行的

通过对消息机制的了解,可以知道Runtime可以动态的添加方法,还可以改变方法的接收者(调用别的对象或者类的方法),或者通过消息转发让多个对象处理一个方法调用等等。

Runtime API应用

方法交换

  • 方法交换也可称为方法调配(method swizzling)-俗称“黑魔法”

  • 由于Objective-C的运行时特性,对象收到消息后要调用的方法实际是在运行期才能解析出来。根据此特性,实际我们可以另方法实现互换,这种技术叫做“方法调配”(method swizzling)。

方法交互使用了此函数 method_exchangeImplementations(Method _Nonnull m1, Method _Nonnull m2)

method_exchangeImplementations的两个参数可以用以下函数获得 class_getInstanceMethod(Class _Nullable __unsafe_unretained cls, SEL _Nonnull name)

  • 举个例子
#import <Foundation/Foundation.h>

@interface FRPerson : NSObject
- (void)methodOne;
- (void)methodTwo;
@end
#import "FRPerson.h"

@implementation FRPerson

- (void)methodOne{
    NSLog(@"实际调用了方法一");
}

- (void)methodTwo{
    NSLog(@"实际调用了方法二");
}

@end

#import <Foundation/Foundation.h>
#import "FRPerson.h"
#import <objc/runtime.h>

int main(int argc, const char * argv[]) {
    @autoreleasepool {
        
        FRPerson *person = [[FRPerson alloc] init];
        
        Method method1 = class_getInstanceMethod([person class], @selector(methodOne));
        
        Method method2 = class_getInstanceMethod([FRPerson class], @selector(methodTwo));
        
        
        method_exchangeImplementations(method1, method2);
        
        
        [person methodOne];//实际调用了方法二
        
        [person methodTwo];//实际调用了方法一
        
        
    }
    return 0;
}


  • 本例子只是说明方法交换怎么使用,在实际的开发中不会这样用。

最常用的是给系统的方法添加一些调试信息或者对系统的方法进行扩展。

还有给第三方框架的一些方法做扩展等等。

例如,拦截所有按钮点击事件(创建一个UIControl的分类)

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

@implementation UIControl (Extension)

+ (void)load
{
    Method method1 = class_getInstanceMethod(self, @selector(sendAction:to:forEvent:));
    Method method2 = class_getInstanceMethod(self, @selector(fr_sendAction:to:forEvent:));
    method_exchangeImplementations(method1, method2);
}

//要与系统交换的方法
- (void)fr_sendAction:(SEL)action to:(id)target forEvent:(UIEvent *)event
{
    NSLog(@"%@-%@-%@", self, target, NSStringFromSelector(action));
    
    // 调用系统原来的实现(看起来是递归调用,但是已经进行了方法交换之后,又调回了系统的方法)
    [self fr_sendAction:action to:target forEvent:event];

    if ([self isKindOfClass:[UIButton class]]) {
        // 拦截了所有按钮的事件
    }
    
}

@end


字典转模型

  • 使用class_copyIvarList函数获取成员变量列表(包括私有的成员变量)

FRPerson里有很多属性。

#import <Foundation/Foundation.h>

@interface FRPerson : NSObject
@property (assign, nonatomic) int ID;
@property (assign, nonatomic) int weight;
@property (assign, nonatomic) int age;
@property (copy, nonatomic) NSString *name;
@end

给NSObject扩展分类处理字典转模型

#import <Foundation/Foundation.h>

@interface NSObject (Json)

+ (instancetype)fr_objectWithJson:(NSDictionary *)json;

@end
#import "NSObject+Json.h"
#import <objc/runtime.h>

@implementation NSObject (Json)

+ (instancetype)fr_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;
}

@end

根据扩展了类工厂方法创建对象

        // 字典转模型
        NSDictionary *json = @{
                               @"id" : @20,
                               @"age" : @20,
                               @"weight" : @60,
                               @"name" : @"Jack"
//                               @"no" : @30
                               };
        
        FRPerson *person = [FRPerson fr_objectWithJson:json];

设置UITextField占位文字的颜色

  • 使用class_copyIvarList函数获取成员变量列表(包括私有的成员变量)
    unsigned int outCount;
    Ivar *ivars = class_copyIvarList([self.textField class], &outCount);

    for (int i = 0; i < outCount; i ++) {
        Ivar ivar = ivars[i];
        const char *name = ivar_getName(ivar);
        const char *encoding = ivar_getTypeEncoding(ivar);
        NSLog(@"%s,--- %s", name, encoding);
    }
    //通过class_copyIvarList查到placeholderLabel私有成员变量
//placeholderLabel内部属于懒加载,要进行设值才会初始化。
_textField.placeholder = @"占位文字";
//通过KVC设值
[_textField setValue:[UIColor brownColor] forKeyPath:@"placeholderLabel.textColor"];


Runtime API

  • 除了以上的应用,还有其他很多功能,在此列出一些API供大家参考。
类相关
动态创建一个类(参数:父类,类名,额外的内存空间)
Class objc_allocateClassPair(Class superclass, const char *name, size_t extraBytes)

注册一个类(要在类注册之前添加成员变量)
void objc_registerClassPair(Class cls) 

销毁一个类
void objc_disposeClassPair(Class cls)

获取isa指向的Class
Class object_getClass(id obj)

设置isa指向的Class
Class object_setClass(id obj, Class cls)

判断一个OC对象是否为Class
BOOL object_isClass(id obj)

判断一个Class是否为元类
BOOL class_isMetaClass(Class cls)

获取父类
Class class_getSuperclass(Class cls)

成员变量相关
获取一个实例变量信息
Ivar class_getInstanceVariable(Class cls, const char *name)

拷贝实例变量列表(最后需要调用free释放)
Ivar *class_copyIvarList(Class cls, unsigned int *outCount)

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

动态添加成员变量(已经注册的类是不能动态添加成员变量的)
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)

属性相关
获取一个属性
objc_property_t class_getProperty(Class cls, const char *name)

拷贝属性列表(最后需要调用free释放)
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)

方法相关
获得一个实例方法、类方法
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)

浅谈系列-OC对象创建出来到底是怎么样的呢

浅谈系列-OC方法调用到底是个什么流程

浅谈系列-class 、meta-class结构简单理解

浅谈系列 - KVO&KVC到底是怎么样实现的

浅谈系列-分类的结构和加载时机

浅谈系列-load 和 initialize的调用时机和实际运用

浅谈系列-block如何工作的