作者:Mitchell
一、简介
- 在 iOS中可以直接调用某个对象的消息方式有两种:
- 一种是 performSelector:withObject;
- 再一种就是 NSInvocation。
- 第一种方式比较简单,能完成简单的调用。但是对于 >2 个的参数或者有返回值的处理,那就需要做些额外工作才能搞定。那么在这种情况下,我们就可以使用NSInvocation来进行这些相对复杂的操作。
二、使用方式
- (void)viewDidLoad {
[super viewDidLoad];
NSMethodSignature*signature = [ViewController instanceMethodSignatureForSelector:@selector(sendMessageWithNumber:WithContent:)];
NSInvocation*invocation = [NSInvocation invocationWithMethodSignature:signature];
invocation.target = self;
invocation.selector = @selector(sendMessageWithNumber:WithContent:);
NSString*number = @"1111";
[invocation setArgument:&number atIndex:2];
NSString*number2 = @"啊啊啊";
[invocation setArgument:&number2 atIndex:3];
[invocation invoke];
}
- (void)sendMessageWithNumber:(NSString*)number WithContent:(NSString*)content{
NSLog(@"电话号%@,内容%@",number,content);
}
三、封装
- 这里对 NSInvocation 进行了封装,如果想使用,直接下载即可。