iOS message forwarding mechanism

iOS message forwarding mechanism

Describe nouns

Message forwarding mechanism: In iOS, when a user sends a message to a class, that is invoked objc_msgSendwhen the class does not have accepted the method according to runtimethe mechanism, which will be transmitted to the parent of this class until a NSObjectclass.

Call the method

Try scene

The above message forwarding mechanism is runtimeimplemented in the interior, then we want to achieve this operation requires its own how to complete it? iOSAlso provides related API, that is NSInvocation. In addition, in my actual coding practice, I decoupled architecture for the api.
Because decoupled architecture scene in general is relatively large-scale projects, and the project has been more logical and under perfect circumstances was carried out, when the module is the middle layer of the upper class method you want to call, we can use NSInvocationfor message forward, because the underlying system is called api, on the efficiency is very high. If a notice that the readability of the code becomes not so good.

Call an instance method

When carrying out the method call that we need to specify the target class, the target method.

    // 1.获取到目标类
    Class class = NSClassFromString(@"Test");
    // 2.获取到目标SEL 方法
    SEL sel = NSSelectorFromString(@"testMethod");
    // 3.实例化该类
    NSObject *obj = [class new];
    // 4.获取到该类的目标方法签名
    NSMethodSignature *methodSign = [obj methodSignatureForSelector:sel];
    // 5.创建invocation对象
    NSInvocation *invocation = [NSInvocation invocationWithMethodSignature:methodSign];
    // 6.指定该invocation 的调用对象
    [invocation setTarget:obj];
    // 7.指定该invocation 的调用方法
    [invocation setSelector:sel];
    // 8.执行该invocation
    [invocation invoke];
Call the class method

The gap between the calling class methods and instance methods is invocationand method signature invocationof the calling object.

    // 1.获取到目标类
    Class class = NSClassFromString(@"Test");
    // 2.获取到目标SEL 方法
    SEL sel = NSSelectorFromString(@"addMethod");
    // 3.获取到该类的目标方法签名
    NSMethodSignature *methodSign = [class methodSignatureForSelector:sel];
    // 4.创建invocation对象
    NSInvocation *invocation = [NSInvocation invocationWithMethodSignature:methodSign];
    // 5.指定该invocation 的调用对象
    [invocation setTarget:class];
    // 6.指定该invocation 的调用方法
    [invocation setSelector:sel];
    // 7.执行该invocation
    [invocation invoke];
Differences summary
method Target NSMethodSignature
Class Methods Class class Use Class class and SEL to create a signature
Examples of methods Instance of class Class The use of Class instances of the class and to create a signature SEL
Published 17 original articles · won praise 2 · views 10000 +

Guess you like

Origin blog.csdn.net/Abe_liu/article/details/103945037