2009-10-30 41 views

回答

13

有幾個選項,因爲據我所知

  1. 您可以使用NSObject中的performSelector:方法。但是,這對於參數很少或沒有參數的方法來說只是非常有用的。
  2. 使用NSInvocation類。這有點令人費解,但是更加靈活。
  3. 您可能可以使用objc_msgSend(),但由於運行時可能會在幕後執行其他操作,因此直接調用它可能是個壞主意。
+0

權的話,只有'performSelector:','performSelector:withObject:'和'performSelector :withObject:withObject:' - 超過2個參數,它不再是一個可行的選擇。我認爲NextSTEP曾經有一個'performv:'允許變量參數,或者類似的東西,但我不太確定... – ephemient 2009-10-30 19:25:50

+0

當你使用NSInvocation或者切換到使用字典作爲論據。這並不難,只需要幾個電話。 – 2009-10-30 20:04:25

+0

另外,1.如果參數類型都是對象而且返回類型是對象或空 – user102008 2012-05-11 19:17:40

-1
if ([foo respondsToSelector:@selector(bar)]) 
    [foo performSelector:@selector(bar))]; 
3

用於一般用途(方法有返回值和任意數量的參數),使用NSInvocation

if ([target respondsToSelector:theSelector]) { 
    NSInvocation *invocation = [NSInvocation invocationWithMethodSignature: 
     [target methodSignatureForSelector:theSelector]]; 
    [invocation setTarget:target]; 
    [invocation setSelector:theSelector]; 
    // Note: Indexes 0 and 1 correspond to the implicit arguments self and _cmd, 
    // which are set using setTarget and setSelector. 
    [invocation setArgument:arg1 atIndex:2]; 
    [invocation setArgument:arg2 atIndex:3]; 
    [invocation setArgument:arg3 atIndex:4]; 
    // ...and so on 
    [invocation invoke]; 
    [invocation getReturnValue:&retVal]; // Create a local variable to contain the return value. 
}