iOS message forwarding mechanism
Article Directory
Describe nouns
Message forwarding mechanism: In iOS, when a user sends a message to a class, that is invoked objc_msgSend
when the class does not have accepted the method according to runtime
the mechanism, which will be transmitted to the parent of this class until a NSObject
class.
Call the method
Try scene
The above message forwarding mechanism is runtime
implemented in the interior, then we want to achieve this operation requires its own how to complete it? iOS
Also 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 NSInvocation
for 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 invocation
and method signature invocation
of 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 |