OC 底层原理笔记

15 runtime之objc_msgSend详解

2020-01-20  本文已影响0人  zysmoon
面试题
1.讲一下 OC 的消息机制
2.什么是Runtime?平时项目中有用过么?
3.具体应用
前言
Person *person = [[Person alloc] init];
[person personTest];
// objc_msgSend(person, @selector(personTest));
// 消息接收者(receiver):person
// 消息名称:personTest

[Person initialize];
// objc_msgSend([MJPerson class], @selector(initialize));
// 消息接收者(receiver):[MJPerson class]
// 消息名称:initialize

objc_msgSend如果找不到合适的方法进行调用,会报错unrecognized selector sent to instance

objc_msgSend执行流程

objc_msgSend的执行流程可以分为3大阶段

1 objc_msgSend执行流程01-消息发送
1653926-7e182bc2809b423e.png
2 objc_msgSend执行流程02-动态方法解析
1653926-ab7a1d1427a5d290.png

实例代码如下

#import <Foundation/Foundation.h>

@interface CSPersion : NSObject
- (void)test;
- (void)missMethod;
+ (void)eat;
@end

#import "CSPersion.h"
#import <objc/runtime.h>

void dynamicMethodIMP(id self, SEL _cmd) {
    NSLog(@" >> dynamicMethodIMP");
}

@implementation CSPersion

+ (BOOL)resolveInstanceMethod:(SEL)sel {
    NSLog(@" >> Instance resolving %@", NSStringFromSelector(sel));

    if (sel == @selector(missMethod)) {
        class_addMethod([self class], sel, (IMP)dynamicMethodIMP, "v@:");
        return YES;
    }
    return [super resolveInstanceMethod:sel];
}

+ (BOOL)resolveClassMethod:(SEL)sel {
    NSLog(@" >> Class resolving %@", NSStringFromSelector(sel));

    if (sel == @selector(eat)) {
        class_addMethod([self class], sel, (IMP)dynamicMethodIMP, "v@:");
        return YES;
    }
    return [super resolveClassMethod:sel];
}

- (void)test {
    NSLog(@"test ...");
}
@end

运行结果

1653926-5e4921f1eca46bae.png
3 objc_msgSend的执行流程03-消息转发
1653926-41ba10eec689888f.png
生成NSMethodSignature
1653926-cc990761999bc77e.png

代码例子佐证

@interface Cat : NSObject
- (int)test:(int)age;
@end

@implementation Cat
- (int)test:(int)age {
    NSLog(@"%s",__func__);
    return age * age;
}
@end

/** 消息发送 */
@interface Student : NSObject
- (void)test:(int)age;
@end

@implementation Student

//+ (BOOL)resolveInstanceMethod:(SEL)sel
//{
//    class_addMethod(<#Class  _Nullable __unsafe_unretained cls#>, <#SEL  _Nonnull name#>, <#IMP  _Nonnull imp#>, <#const char * _Nullable types#>)
//}

- (NSMethodSignature *)methodSignatureForSelector:(SEL)aSelector {
    if (aSelector == @selector(test:)) {

        // 测试一
//        return [NSMethodSignature signatureWithObjCTypes:"v20@0:8i16"];

        // 测试二
//        return [NSMethodSignature signatureWithObjCTypes:"i@:I"];

        // 测试三
//        return [[[Cat alloc] init] methodSignatureForSelector:aSelector];
    }
    return [super methodSignatureForSelector:aSelector];
}

- (void)forwardInvocation:(NSInvocation *)anInvocation {
    // 参数顺序:receiver、selector、other arguments

    // 测试一
//    int age;
//    [anInvocation getArgument:&age atIndex:2];
//    NSLog(@"%d", age + 10);

    // 测试二
    // anInvocation.target == [[MJCat alloc] init]
    // anInvocation.selector == test:
    // anInvocation的参数:15
//    [[[Cat alloc] init] test:15];

    // 测试三
    [anInvocation invokeWithTarget:[[Cat alloc] init]];
    int ret;
    [anInvocation getReturnValue:&ret];
    NSLog(@"%d", ret);
}
@end

int main(int argc, const char * argv[]) {
    @autoreleasepool {
        // 2.消息转发
        Student *stu = [[Student alloc] init];
        [stu test:10];
    }
    return 0;
}

运行结果如下

1653926-bccd7440107a71aa.png
4 objc_msgSend-类方法消息转发
@interface CSCat : NSObject
+ (void)test;
- (void)test;
@end

@implementation CSCat
+ (void)test {
    NSLog(@"%s", __func__);
}

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

/** 类方法的转发过程 */
@interface CSPerson : NSObject
+ (void)test;
@end

@implementation CSPerson

+ (id)forwardingTargetForSelector:(SEL)aSelector {
    // objc_msgSend([[MJCat alloc] init], @selector(test))
    // [[[MJCat alloc] init] test]
    // 该方法显示与注释后有不同的结果
//    if (aSelector == @selector(test)) {
//        return [[CSCat alloc] init];
//    }

    return [super forwardingTargetForSelector:aSelector];
}

+ (NSMethodSignature *)methodSignatureForSelector:(SEL)aSelector {
    if (aSelector == @selector(test)) {
        return [NSMethodSignature signatureWithObjCTypes:"v@:"];
    }

    return [super methodSignatureForSelector:aSelector];
}

+ (void)forwardInvocation:(NSInvocation *)anInvocation {
    NSLog(@"1123");
}
@end

int main(int argc, const char * argv[]) {
    @autoreleasepool {
        [CSPerson test];
    }
    return 0;
}

运行结果

1653926-207003639eaaa6b9.png
synthesize关键字

synthesize会默认帮我们生成带下划线的变量和set方法get方法

@implementation Person

@synthesize age = _age;

- (void)setAge:(int)age {
    _age = age;
}

-(int)age {
    return _age;
}
@end

这个是很久之前Xcode版本需要做的事情,现在都不需要了,Xcode都已经帮我们做好了。

dynamic关键字

dynamic提醒编译器不要自动生成setter和getter的实现、不要自动生成成员变量

@dynamic weight;

运行结果

1653926-3e7b5e9844c8726c.png
@implementation Person

@dynamic weight;

void setWeight(id self, SEL _cmd, int weight) {
    NSLog(@"weight is %d", weight);
}

int weight(id self, SEL _cmd) {
    return 120;
}

+ (BOOL)resolveInstanceMethod:(SEL)sel {
    if (sel == @selector(setWeight:)) {
        class_addMethod(self, sel, (IMP)setWeight, "v@:I");
        return YES;
    } else if (sel == @selector(weight)) {
        class_addMethod(self, sel, (IMP)weight, "i@:");
        return YES;
    }
    return [super resolveInstanceMethod:sel];
}
@end

int main(int argc, const char * argv[]) {
    @autoreleasepool {
        Person *per = [[Person alloc] init];
        per.age = 100;
        NSLog(@"age = %d",per.age);

        per.weight = 200;
        NSLog(@"weight = %f",per.weight);
    }
    return 0;
}

运行结果

1653926-68f67d03c19b621d.png

本文参考:
路飞_Luck (https://www.jianshu.com/p/07f7b96bb03f)
以及借鉴MJ的教程视频
非常感谢.


项目连接地址 - runtime-object_msgSend
项目连接地址 - runtim-dynamic关键字

上一篇下一篇

猜你喜欢

热点阅读