1.直接调用
[someObj foo];
2.NSInvocation 的使用
NSMethodSignature *signature = [someObj methodSignatureForSelector:@selector(foo:)];
NSInvocation *invocation = [NSInvocation invocationWithMethodSignature:signature];
invocation = @selector(foo:);//必须设置
BOOL arg = YES;
[invocation setArgument:&arg atIndex:2];
[invocation invokeWithTarget:someObj];
会遇到的问题
- 创建NSMethodSignature 的时候有可能会为空,
- 原因:[NSMethodSignature instanceMethodSignatureForSelector:@"foo"],用了这个NSMethodSignatureClass
- 解决办法:要使用你要获取的SEL所在的Class或者Instance 调用instanceMethodSignatureForSelector:获取方法签名
[yourClassInstance methodSignatureForSelector:@"foo"];
[YourClass instanceMethodSignatureForSelector:@"foo"];
- Target必须要设置,方法签名只是方法签名不包含Target
invocation.target = someObj;
[invocation invokeWithTarget:someObj];
- 设置参数的index从2开始,0是self,1是SEL
- 传递基本数据类型参数时,要传递指针类型
BOOL arg = YES;
[invocation setArgument:&arg atIndex:2];
NSString *arg3 = @"c";
[invocation setArgument:&arg3 atIndex:3];
- 获取返回值
if (signature.methodReturnLength > 0) {
id ret;
[invocation getReturnValue:&ret];
}
3. NSInvocationOperation
类似NSInvocation,用NSOperation封装了NSInvocation,可以队列操作或者线程批量执行
NSInvocationOperation *invocationOp = [[NSInvocationOperation alloc] initWithTarget:self selector:@selector(fooSel) object:nil];
NSString *str = @"arg1";
[invocationOp.invocation setArgument:&str atIndex:2];
[invocationOp start];
NSInteger ret = 0;
[invocationOp.result getValue:&ret]; //获取返回值要调用这个方法
4.performSelector
- 如何传递基本数据类型
- 原则上不可以,目前没有找到办法,只能选择其他方式
- 如何传递多参数
- 把参数放入到字典或着数组
5.objc_msgSend函数指针
void (*msgSendPointer)(id,SEL,BOOL) = (void (*)(id,SEL,BOOL))objc_msgSend;
msgSendPointer(self,@selector(foo:),NO);