NSInvocation消息调用
2018-09-29 本文已影响0人
淡燃
NSInvocation 是一个消息调用类, 用来调用某个类的某个方法
NSMethodSignature : 方法签名,记录了方法的返回值的类型和参数的类型
例子
- (void)viewDidLoad
{
[super viewDidLoad];
SEL selector = @selector(addTextContent:atIndex:toContent:);
//初始化一个方法签名,需要用Class去调,通过Class可以相应方法的返回值和参数的类型
NSMethodSignature *signature = [[self class] instanceMethodSignatureForSelector:selector];
NSLog(@"numberOfArguments:%ld", signature.numberOfArguments);
for (NSInteger i=0; i<signature.numberOfArguments; i++) {
const char * argumentType = [signature getArgumentTypeAtIndex:i];
NSLog(@"argumentType: %@ index: %ld", [NSString stringWithUTF8String:argumentType], i);
}
//初始化NSInvocation
NSInvocation *invocation = [NSInvocation invocationWithMethodSignature:signature];
invocation.target = self;
invocation.selector = selector;
//设置参数
NSString *text = @"haa";
NSNumber *index = @(10);
NSString *content = @"content";
//0代表target 1代表selector,已经被占用,所以从2开始
[invocation setArgument:&text atIndex:2];
[invocation setArgument:&index atIndex:3];
[invocation setArgument:&content atIndex:4];
//打印0和1位置的参数
id __unsafe_unretained target;
[invocation getArgument:&target atIndex:0];
NSLog(@"target: %@", target);
SEL sel;
[invocation getArgument:&sel atIndex:1];
NSLog(@"selector: %@", NSStringFromSelector(sel));
//调用invocation执行方法
[invocation invoke];
//获取方法返回值
NSArray * __unsafe_unretained tempResultSet;
[invocation getReturnValue:&tempResultSet];
NSArray *resultSet = tempResultSet;
NSLog(@"%@", resultSet);
}
- (NSString *)addTextContent:(NSString *)text atIndex:(NSNumber *)index toContent:(NSString *)content
{
return [NSString stringWithFormat:@"%@ %@ %@", text, index, content];
}
log打印
2018-09-29 15:59:03.257574+0800 testInvocation[44683:3741832] numberOfArguments:5
2018-09-29 15:59:03.257844+0800 testInvocation[44683:3741832] argumentType: @ index: 0
2018-09-29 15:59:03.257998+0800 testInvocation[44683:3741832] argumentType: : index: 1
2018-09-29 15:59:03.258135+0800 testInvocation[44683:3741832] argumentType: @ index: 2
2018-09-29 15:59:03.258311+0800 testInvocation[44683:3741832] argumentType: @ index: 3
2018-09-29 15:59:03.258414+0800 testInvocation[44683:3741832] argumentType: @ index: 4
2018-09-29 15:59:03.258646+0800 testInvocation[44683:3741832] target: <ViewController: 0x7fb1e8512c10>
2018-09-29 15:59:03.258796+0800 testInvocation[44683:3741832] selector: addTextContent:atIndex:toContent:
2018-09-29 15:59:03.259050+0800 testInvocation[44683:3741832] returnValue: haa 10 content