1.直接調(diào)用
[someObj foo];
2.NSInvocation 的使用
NSMethodSignature *signature = [someObj methodSignatureForSelector:@selector(foo:)];
NSInvocation *invocation = [NSInvocation invocationWithMethodSignature:signature];
invocation = @selector(foo:);//必須設(shè)置
BOOL arg = YES;
[invocation setArgument:&arg atIndex:2];
[invocation invokeWithTarget:someObj];
會(huì)遇到的問(wèn)題
- 創(chuàng)建NSMethodSignature 的時(shí)候有可能會(huì)為空,
- 原因:[NSMethodSignature instanceMethodSignatureForSelector:@"foo"]低匙,用了這個(gè)NSMethodSignatureClass
- 解決辦法:要使用你要獲取的SEL所在的Class或者Instance 調(diào)用instanceMethodSignatureForSelector:獲取方法簽名
[yourClassInstance methodSignatureForSelector:@"foo"];
[YourClass instanceMethodSignatureForSelector:@"foo"];
- Target必須要設(shè)置一汽,方法簽名只是方法簽名不包含Target
invocation.target = someObj;
[invocation invokeWithTarget:someObj];
- 設(shè)置參數(shù)的index從2開始避消,0是self,1是SEL
- 傳遞基本數(shù)據(jù)類型參數(shù)時(shí)召夹,要傳遞指針類型
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,可以隊(duì)列操作或者線程批量執(zhí)行
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]; //獲取返回值要調(diào)用這個(gè)方法
4.performSelector
- 如何傳遞基本數(shù)據(jù)類型
- 原則上不可以监憎,目前沒(méi)有找到辦法纱意,只能選擇其他方式
- 如何傳遞多參數(shù)
- 把參數(shù)放入到字典或著數(shù)組
5.objc_msgSend函數(shù)指針
void (*msgSendPointer)(id,SEL,BOOL) = (void (*)(id,SEL,BOOL))objc_msgSend;
msgSendPointer(self,@selector(foo:),NO);