关于在iOS中AOP思想与组件化相结合的架构模式探索(AOP实现热更新)(三)NSInvocation的使用
NSInvocation是调用函数的另一种方式,它将调用者,函数名,参数封装到一个对象,然后通过一个invoke函数来执行被调用的函数,其思想就是命令者模式,将请求封装成对象。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27
| //封装方法 SEL selector = @selector(test2:); //初始化方法签名 NSMethodSignature *signature = [[self class] instanceMethodSignatureForSelector:selector]; // NSInvocation : 利用一个NSInvocation对象包装一次方法调用(方法调用者、方法名、方法参数、方法返回值) NSInvocation *invocation = [NSInvocation invocationWithMethodSignature:signature]; //设置调用者 invocation.target = self; //设置调用方法 invocation.selector = selector; //设置参数 NSString * object = @"hello it's invocation method"; ////指定参数,以指针方式,并且第一个参数的起始index是2,因为index为0,1的分别是self和selector [invocation setArgument:&object atIndex:2]; //调用方法 [invocation invoke];
//返回值,这里的处理比较复杂 具体请百度 const char *returnType = signature.methodReturnType; id returnValue; NSUInteger length = [signature methodReturnLength]; void *buffer = (void *)malloc(length); [invocation getReturnValue:buffer]; returnValue = [NSValue valueWithBytes:buffer objCType:returnType];//returnType为@即为字符串 void *ret; [invocation getReturnValue:&ret]; NSLog(@"result=%@",(__bridge id)(ret));
|
1 2 3 4
| - (NSString *)test2:(NSString *)str{ NSLog(@"test2 : %@",str); return str; }
|
运行可见:
1 2
| 2018-09-07 16:26:38.194153+0800 Demo1Method[39694:3046042] test2 : hello it's invocation method 2018-09-07 16:26:38.194288+0800 Demo1Method[39694:3046042] result=hello it's invocation method
|
那么我们如何使用NSInvocation去实现通过字符串生成的方法调用呢?
挖坑:
1.我们需要判断是实例方法还是类方法
2.指定参数的封装,如果有多个该怎么指定
3.返回值的处理