美文网首页
Runtime主要用处

Runtime主要用处

作者: 谁在呼叫贱队 | 来源:发表于2021-05-09 14:03 被阅读0次

深入理解Objective-C Runtime机制


一:消息转发流程和机制

1、实例方法:本类的缓存方法列表->本类的方法列表->父类的缓存方法列表->父类的方法列表->NSObject->消息转发
2、类方法:本类的元类的缓存方法列表->本类的元类的方法列表->元类的父类的缓存方法列表->元类的父类的方法列表->NSObject->消息转发
消息转发一:动态解析

//Person.h
@interface Person : NSObject
//在.m文件中添加了@dynamic,所以不会自动添加setter和getter方法
@property(assign,nonatomic)NSInteger weight;
@end

//Person.m
@implementation Person
@dynamic weight;

void setPropertyDynamic(id self,SEL _cmd){    
    NSLog(@"This is a dynamic method added for Person instance");
}
//resolveClassMethod 类方法。resolveInstanceMethod 实例方法  需要自己添加
+ (BOOL)resolveInstanceMethod:(SEL)sel{    
    if (sel == @selector(setWeight:)){
        //将方法动态添加到缓存
        class_addMethod([self class], sel,(IMP)setPropertyDynamic, "v@:");
        return YES;
    }
    return [super resolveInstanceMethod:sel];
}
@end

// main函数中调用
Person *p = [[Person alloc]init] ;
p.weight = 100;

消息转发二:可以通过SEL名调用其他方法未声明的方法 - 重定向

//Person.m

// Person类重写重定向方法,将weight的getter方法重定向到People类,其他方法不处理
- (id)forwardingTargetForSelector:(SEL)aSelector{
    if (aSelector == @selector(weight)) {
        People *people = [People new];
        return people;
    }
    id target = [super forwardingTargetForSelector:aSelector];
    return target;
}

//People.h
@interface People : NSObject
@end

//People.m
@implementation People
- (NSInteger)weight {
    return 666;
}
@end

// main函数中调用
Person *person = [[Person alloc] init] ;
NSInteger weightValue = person.weight;
NSLog(@"%ld",weightValue); //666

消息转发三:自动向父类访问,直到NSObject - 消息转发

//Person.h
//在.m文件中添加了@dynamic,所以下面的属性不会自动添加setter和getter方法
@property(copy,nonatomic)NSString *identifier;


//Person.m
@dynamic identifier;

- (NSMethodSignature *)methodSignatureForSelector:(SEL)aSelector
{
    if (aSelector == @selector(setIdentifier:) || aSelector == @selector(identifier) ) {
        NSMethodSignature *sign = [People instanceMethodSignatureForSelector:aSelector];
        return sign;
    }
    return nil;
}
- (void)forwardInvocation:(NSInvocation *)anInvocation{
    People *people = [[People alloc]init];
    if ([people respondsToSelector:[anInvocation selector]]) {
        [anInvocation invokeWithTarget:people];
    }else{
        [super forwardInvocation:anInvocation];
    }
}


//People.h
@property(copy,nonatomic)NSString *identifier;


// main函数中调用
Person *person = [[Person alloc] init];
person.identifier = @"yzk whlpkk";
NSLog(@"%@",person.identifier); //null

这时runtime消息转发结束。如果还是处理不了这个SEL,最后会调用:

//抛出异常警告方法指向为空
-(void)doesNotRecognizeSelector:(SEL)sel {}

再来说一下消息转发和重定向的区别。

重定向只能重定向到一个对象,但是消息转发,可以同时对多个对象转发,只需要[anInvocation invokeWithTarget:]多个target即可。
重定向的target必须要有一个,如果是nil,则target就是当前实例。消息转发
可以不转发,即不调用[anInvocation invokeWithTarget:],不会crash,但是消息转发的methodSignatureForSelector:方法签名不能返回nil,否则会crash。

二:Method Swizzling(方法替换)

Method Swizzling原理:

Method Swizzing是发生在运行时的,主要用于在运行时将两个Method进行交换,我们可以将Method Swizzling代码写到任何地方,但是只有在这段                     
Method Swilzzling代码执行完毕之后互换才起作用。

实现方法:

+(void)load{
    [super load];
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        Class class = object_getClass((id)self);
        //获取需要修改的方法
        Method imgNameMethod = class_getClassMethod(class, @selector(imageNamed:));
        //获取需要交换的方法-必须实现
        Method ym_imgNameMethod = class_getClassMethod(class, @selector(ym_imageNamed:));
        //基本就是说这可以加入新的方法到一个类里面
        BOOL didAddMethod = class_addMethod(class, @selector(imageNamed:), method_getImplementation(ym_imgNameMethod), method_getTypeEncoding(ym_imgNameMethod));
        //如果返回成功:则说明被替换方法没有存在.也就是被替换的方法没有被实现,我们需要先把这个方法实现,然后再执行我们想要的效果,用我们自定义的方法去替换被替换的方法
        if (didAddMethod) {
            //class_replaceMethod这个方法. class_replaceMethod本身会尝试调用class_addMethod和method_setImplementation,所以直接调用class_replaceMethod就可以了
            class_replaceMethod(class, @selector(ym_imageNamed:), method_getImplementation(imgNameMethod), method_getTypeEncoding(imgNameMethod));
        }else{
            //开始交换方法实现
            method_exchangeImplementations(imgNameMethod, ym_imgNameMethod);
        }
    });
}


+(UIImage *)ym_imageNamed:(NSString *)name{
    UIImage *image = [UIImage ym_imageNamed:name];
    if (image) {
        NSLog(@"runtime添加额外功能---加载成功");
    }else{
        NSLog(@"runtime添加额外功能---加载失败");
    }
    return image;
}

相关文章

  • Runtime主要用处

    深入理解Objective-C Runtime机制 一:消息转发流程和机制 1、实例方法:本类的缓存方法列表->本...

  • OC -> Runtime

    Runtime简介 Runtime用处 Runtime实践 Runtime 类方法调用实现。Person * p ...

  • iOS runtime 之跳转页面以及动态添加属性

    序言 runtime 的主要用处有以下几点: 给分类添加属性 消息转发机制 动态交换方法的实现 手动实现多继承(o...

  • iOS面试-Runtime简介

    本文主要介绍runtime的五点 Runtime简介 Runtime(消息机制) Runtime方法调用流程 Ru...

  • iOS-Runtime的用处

    JsonModel封装, 权限控制 对于系统控件扩展,需要保存某些属性. 但是在category中不能实现时.//...

  • Runtime-基础与应用

    主要内容 Runtime 基础 Runtime 应用 Runtime 基础 Objective-C 语言将决定尽可...

  • runtime的理解(二)

    主要内容 利用 runtime 交换方法 利用 runtime 动态添加方法 利用 runtime 动态添加属性 ...

  • Runtime基础知识

    Runtime相关的知识主要从以下几个问题入手吧 Runtime是何物 Runtime中的结构体 Runtime中...

  • 简单面试总结

    iOS面试主要方面 runtime1.1 runtime能做什么。1.2 runtime包含的内容。1.3 cat...

  • iOS runtime主要函数

    类相关操作函数 实例相关操作函数 属性操作相关函数 方法操作相关函数 选择器相关的操作函数 协议相关的操作函数 b...

网友评论

      本文标题:Runtime主要用处

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