在iOS中,可以使用performSelector
系列方法來(lái)對(duì)某個(gè)類(lèi)來(lái)進(jìn)行調(diào)用方法。
- (id)performSelector:(SEL)aSelector;
- (id)performSelector:(SEL)aSelector withObject:(id)object;
- (id)performSelector:(SEL)aSelector withObject:(id)object1 withObject:(id)object2;
這種調(diào)用有一定局限性,只能最多傳遞2個(gè)參數(shù)。一旦參數(shù)多了,就無(wú)能為力了。但是我們還可以使用NSInvocation
來(lái)進(jìn)行方法調(diào)用。
NSInvocation
文檔描述
An NSInvocation is an Objective-C message rendered static, that is, it is an action turned into an object. NSInvocation objects are used to store and forward messages between objects and between applications, primarily by NSTimer objects and the distributed objects system.
下面來(lái)看一段示例代碼
//獲取方法簽名
NSMethodSignature *methondSign = [[self class]instanceMethodSignatureForSelector:@selector(sayHelloTo:)];
//通過(guò)方法簽名獲取調(diào)用
NSInvocation *invocation = [NSInvocation invocationWithMethodSignature:methondSign];
//設(shè)置target和selector
[invocation setTarget:self];
[invocation setSelector:@selector(sayHelloTo:)];
//設(shè)置參數(shù)
NSString *s = @"world";
[invocation setArgument:&s atIndex:2];
//執(zhí)行調(diào)用
[invocation invoke];
//如果有延時(shí)操作 可以retain參數(shù)不被釋放
// [invocation retainArguments];
//如果有返回值 如果是void 會(huì)野指針
char *type = methondSign.methodReturnType;
if (!strcmp(type, @encode(void))) {
//沒(méi)有返回值
}
else
{
if (!strcmp(type, @encode(id))) {
//對(duì)象類(lèi)型
NSString *returnValue = nil;
[invocation getReturnValue:&returnValue];
NSLog(@"return value = %@", returnValue);
}
}
1、獲取方法簽名
2、通過(guò)方法來(lái)獲取NSInvocation
對(duì)象
3、設(shè)置NSInvocation
的target和selector
4、設(shè)置參數(shù),參數(shù)從index為2開(kāi)始,因?yàn)榍懊?個(gè)參數(shù)被self,_cmd占用。
5、調(diào)用invoke
來(lái)執(zhí)行調(diào)用(如果要延時(shí)操作可以使用retain來(lái)持有不被釋放)
6、(如果需要獲取返回值)可以先獲取返回值type,如果是有類(lèi)型的可以使用@encode來(lái)進(jìn)行比較,來(lái)獲取具體的返回值類(lèi)型,隨后調(diào)用getReturnValue
來(lái)得到返回值。