前提:
在 iOS中可以直接調(diào)用某個(gè)對象的消息方式有兩種:
一種是performSelector:withObject
逗噩;
再一種就是NSInvocation
送矩。
第一種方式比較簡單,能完成簡單的調(diào)用约啊。但是對于>2個(gè)的參數(shù)或者有返回值的處理耗帕,那performSelector:withObject
就顯得有點(diǎn)有心無力了校仑,那么在這種情況下忠售,我們就可以使用NSInvocation
來進(jìn)行這些相對復(fù)雜的操作
NSInvocation的基本使用
//簡單調(diào)用 如果只是簡單調(diào)用,直接用performSelector就可以了
SEL myMethod = @selector(myLog);
//創(chuàng)建一個(gè)函數(shù)簽名迄沫,這個(gè)簽名可以是任意的稻扬。但需要注意,簽名的函數(shù)的參數(shù)數(shù)量要和調(diào)用的一致羊瘩。
NSMethodSignature *sig = [NSNumber instanceMethodSignatureForSelector:@selector(init)];
//通過簽名初始化
NSInvocation *invocation = [NSInvocation invocationWithMethodSignature:sig];
//設(shè)置target
[invocation setTarget:self];
//設(shè)置selector
[invocation setSelector:myMethod];
//消息調(diào)用
[invocation invoke];
//調(diào)用方法
- (void)myLog
{
NSLog(@"%s",__FUNCTION__);
NSLog(@"調(diào)用了方法");
}
執(zhí)行方法結(jié)果如果:
NSInvocation的多參數(shù)調(diào)用
/*
多參數(shù)調(diào)用
這個(gè)才是發(fā)揮出NSInvocation的作用
*/
SEL myMethod1 = @selector(myLog1:parm:parm:);
NSMethodSignature *sig1 = [[self class] instanceMethodSignatureForSelector:myMethod1];
//通過簽名初始化
NSInvocation *invocation1 = [NSInvocation invocationWithMethodSignature:sig1];
//設(shè)置target
[invocation1 setTarget:self];
[invocation1 setSelector:myMethod1];
//設(shè)置其它參數(shù)
int a = 1;
int b = 2;
int c = 3;
[invocation1 setArgument:&a atIndex:2];
[invocation1 setArgument:&b atIndex:3];
[invocation1 setArgument:&c atIndex:4];
//retain 所有參數(shù)泰佳,防止參數(shù)被釋放dealloc
[invocation1 retainArguments];
//消息調(diào)用
[invocation1 invoke];
//調(diào)用方法
- (void)myLog1:(int)a parm:(int)b parm:(int)c
{
NSLog(@"%s",__FUNCTION__);
NSLog(@"a = %d b = %d c = %d",a,b,c);
}
打印結(jié)果如圖:
NSInvocation的有返回值調(diào)用
/*
NSInvocation有返回值
*/
//大體和多參數(shù)調(diào)用一樣。
SEL myMethod2 = @selector(myLog2:parm:parm:);
NSMethodSignature *sig2 = [[self class] instanceMethodSignatureForSelector:myMethod2];
//通過簽名初始化
NSInvocation *invocation2 = [NSInvocation invocationWithMethodSignature:sig2];
//設(shè)置target
[invocation2 setTarget:self];
[invocation2 setSelector:myMethod2];
//設(shè)置其它參數(shù)
int d = 10;
int e = 11;
int f = 12;
[invocation2 setArgument:&d atIndex:2];
[invocation2 setArgument:&e atIndex:3];
[invocation2 setArgument:&f atIndex:4];
//retain 所有參數(shù)尘吗,防止參數(shù)被釋放dealloc
[invocation2 retainArguments];
//消息調(diào)用
[invocation2 invoke];
/*
有返回值的時(shí)候逝她,需要先消息調(diào)用,再去獲取返回值睬捶!~
*/
//定義一個(gè)返回值
int sum;
//獲取返回值
[invocation2 getReturnValue:&sum];
//打印返回值
NSLog(@"sum = %d",sum);
//調(diào)用方法
- (int)myLog2:(int)d parm:(int)e parm:(int)f
{
NSLog(@"%s",__FUNCTION__);
NSLog(@"d = %d e = %d f = %d",d,e,f);
return d+e+f;
}
打印結(jié)果如圖: