OC方法调用流程

基本概括

OC中的方法调用其实都是转成了objc_msgSend函数的调用,给receiver(方法调用者)发送了一条消息(selector方法名)

三大阶段

  • 消息发送(当前类,父类中查找)
  • 动态方法解析
  • 消息转发
    1、消息发送


    1111.png

    2、动态方法解析


    2222.png
+ (BOOL)resolveInstanceMethod:(SEL)sel{
    if(sel == @selector(setAge:)){
        NSLog(@"resolveInstanceMethod %@", NSStringFromSelector(sel));
        Method method = class_getInstanceMethod(self, @selector(setAge1:));
        class_addMethod(self, sel, method_getImplementation(method), method_getTypeEncoding(method));
        return YES;
    }
//    else if(sel == @selector(age)){
//        Method method = class_getInstanceMethod(self, @selector(getAge1));
//        class_addMethod(self, sel, method_getImplementation(method), method_getTypeEncoding(method));
//        return YES;
//    }
    return [super resolveInstanceMethod:sel];
}

3、消息转发
先执行forwardingTargetForSelector,没有匹配再执行methodSignatureForSelector。


3333.png
- (id)forwardingTargetForSelector:(SEL)aSelector{
    if(aSelector == @selector(age)){
        return [[MJOther alloc] init];
    }
    return [super forwardingTargetForSelector:aSelector];
}

- (NSMethodSignature *)methodSignatureForSelector:(SEL)aSelector{
    if(aSelector == @selector(age)){
        return [[[MJOther alloc] init] methodSignatureForSelector:@selector(age)];
    }
    return [super methodSignatureForSelector:aSelector];
}

- (void)forwardInvocation:(NSInvocation *)anInvocation{
    if(anInvocation.selector == @selector(age)){
        [anInvocation invokeWithTarget:[[MJOther alloc] init]];
    }
    
}

你可能感兴趣的:(OC方法调用流程)