底层原理:Runtime之API

2022-06-05  本文已影响0人  飘摇的水草
API - 类
#import <objc/runtime.h>

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
    //创建类
    Class newClass = objc_allocateClassPair([NSObject class],"Dog",0);
    //第4个参数表示为对齐,3个为几个字节
    //添加成员变量
    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(@"age = %@, weight = %@",[dog valueForKey:@"_age"],[dog valueForKey:@"_weight"]);

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

    return YES;
}
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
    // Override point for customization after application launch.
    
    
    Person *person = [[Person alloc]init];
    [person run];

    object_setClass(person,[Car class]);
    [person run];
    
    return YES;
}

上面的代码经过 object_setClassperson 变为 Car 类型的,控制台的输出如下:

2022-06-05 16:27:36.180629+0800 TestPod[41697:189747] -[Person run]
2022-06-05 16:30:03.061300+0800 TestPod[41697:189747] -[Car run]

其isa指针变化如下图所示:

NSLog(@"%d %d %d",object_isClass(person),object_isClass([Person class]), object_isClass(object_getClass([Person class])));

上面除了 person 不是 Class 外,其他两个都是 Class

API - 成员变量

用法如下:

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

输出结果:

2022-06-07 19:57:59.023243+0800 TestPod[14761:1648955] _age i
    //成员变量的数值
    unsigned int count;
    Ivar *ivars = class_copyIvarList([Person class], &count);
    for (int i = 0; i < count; i++)
    {
        //取出i位置的成员变量
        Ivar ivar = ivars[i];
        NSLog(@"%s %s",ivar_getName(ivar),ivar_getTypeEncoding(ivar));
    }
    //runtime中调用copy或者create创建出来的都需要释放
    free(ivars);

输出结果为:

2022-06-09 10:30:55.223196+0800 TestPod[2000:400561] _age i
2022-06-09 10:30:55.223232+0800 TestPod[2000:400561] _name @"NSString"

通过上面的办法,我们可以输出系统类的成员属性,并通过其他方式来修改它,例如下面这个是通过 KVC 的方式来修改 TextFieldplaceHolder 的文字颜色

    //成员变量的数值
    unsigned int count;
    Ivar *ivars = class_copyIvarList([UITextField class], &count);
    for (int i = 0; i < count; i++)
    {
        //取出i位置的成员变量
        Ivar ivar = ivars[i];
        NSLog(@"---%s %s",ivar_getName(ivar),ivar_getTypeEncoding(ivar));
    }
    //runtime中调用copy或者create创建出来的都需要释放
    free(ivars);

    UITextField *textField = [[UITextField alloc]init];
    textField.placeholder = @"11111";
    
    //下面这个是拿到打印出来的placeholder相关的一个属性
    UILabel *placeHolderLabel = [textField valueForKey:@"_placeHolderLabel"];
    placeHolderLabel.textColor = [UIColor redColor];
    //或者用下面的办法
    [textField setValue:[UIColor redColor] forKey:@"_placeHolderLabel.textColor"];

还可以通过给 'NSObject' 添加类别的方式来解析属性值,如下所示:

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

@implementation NSObject (Json)

+ (instancetype)My_objectWithJson:(NSDictionary *)dict
{
    id obj = [[self alloc]init];
    
    unsigned int count;
    Ivar *ivars = class_copyIvarList(self, &count);
    for (int i = 0; i < count; i++)
    {
        Ivar ivar = ivars[i];
        NSString *name = [NSString stringWithUTF8String:ivar_getName(ivar)];
        NSMutableString *str = [NSMutableString stringWithString:name];
        [str deleteCharactersInRange:NSMakeRange(0, 1)];
        
        //设值
        [obj setValue:dict[str] forKey:name];
        
    }
    return obj;;
}

然后解析属性值,这样即可:

Person *per = [Person My_objectWithJson:dict];
//设置和获取成员变量的值
Ivar nameIvar = class_getInstanceVariable([Person class],"_name");
Person *p = [[Person alloc]init];
object_setIvar(p, nameIvar, @"123");
object_getIvar(p, nameIvar);
object-setIvar(p, ageIvar, (_bridge id)(void *)10);
NSLog(@"%@",p.name);

//输出结果
2022-06-07 20:13:33.309974+0800 TestPod[15127:1666081] 123
方法的API

获得一个实例方法、类方法

方法实现相关操作

#import "Person.h"

@implementation Person

- (void)run
{
    NSLog(@"%s",__func__);
}

- (void)test
{
    NSLog(@"%s",__func__);
}

@end

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

int main(int argc, const char * argv[]) {
    @autoreleasepool {

        Person *person = [[Person alloc]init];
        Method runMethod = class_getInstanceMethod([Person class], @selector(run));
        Method testMethod = class_getInstanceMethod([Person class], @selector(test));
        method_exchangeImplementations(runMethod, testMethod);
        [person run];
    }
    return 0;
}

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

·动态添加方法

动态替换方法

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

void myRun()
{
    NSLog(@"myRun");
}

int main(int argc, const char * argv[]) {
    @autoreleasepool {

        Person *person = [[Person alloc]init];
        
        class_replaceMethod([Person class], @selector(run), (IMP)myRun, "v");
        //或者用下面这种方式
        class_replaceMethod([Person class], @selector(run), imp_implementationWithBlock(^{
            NSLog(@"123123");
        }), "v");
        [person run];
    }
    return 0;
}

获取方法的相关信息(带有copy的需要弱用free去释放)

Runtime总结

1.什么是Runtime?平时项目中有用过么?

  1. 具体应用
例子

如果想要监听系统的方法,或者在系统方法的基础上做一些改变,可以使用下面的方法,这种方式就叫 HOOK

监听按钮的点击事件

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    NSArray *array = [NSArray arrayWithObjects:@"1",nil];
    
    UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
    button.frame = CGRectMake(100, 100, 80, 40);
    button.backgroundColor = [UIColor redColor];
    [button addTarget:self action:@selector(buttonClick) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:button];
    
}

- (void)buttonClick
{
    NSLog(@"%s",__func__);
}

@end

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

@implementation UIControl (Extention)

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

- (void)mySendAction:(SEL)action to:(id)target forEvent:(UIEvent *)event
{
    NSLog(@"%@---%@---%@",self,target,NSStringFromSelector(action));
    if ([self isKindOfClass:[UIButton class]])
    {
        [self mySendAction:action to:target forEvent:event];
    }
}
@end

防止数组里添加 nil 的对象,这里注意虽然类型是 NSMutableArray 类型的,但其底层却不是这样的,故在交换之前最好通过 [array class] 来打印一下对象的类型

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    NSObject *obj = nil;

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

@end

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

@implementation NSArray (Extension)

+ (void)load
{
    Class class = NSClassFromString(@"__NSArrayM");
    Method method1 = class_getInstanceMethod(class, @selector(insertObject:atIndex:));
    Method method2 = class_getInstanceMethod(class, @selector(mj_insertObject:atIndex:));
    method_exchangeImplementations(method1, method2);
}

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

@end

通过上面两个例子我们可以尝试修改系统字体

上一篇 下一篇

猜你喜欢

热点阅读