我不確定這是可能的,但在紅寶石中,您可以動態地調用一個方法,使用發送是否有一個客觀的C「等效」紅寶石的發送方法?
如果我想要調用該對象的酒吧方法,富,我可以用
foo.send("bar")
是否有使用Objective-C的做類似事情的方法嗎?
tks!
我不確定這是可能的,但在紅寶石中,您可以動態地調用一個方法,使用發送是否有一個客觀的C「等效」紅寶石的發送方法?
如果我想要調用該對象的酒吧方法,富,我可以用
foo.send("bar")
是否有使用Objective-C的做類似事情的方法嗎?
tks!
有幾個選項,因爲據我所知
performSelector:
方法。但是,這對於參數很少或沒有參數的方法來說只是非常有用的。objc_msgSend()
,但由於運行時可能會在幕後執行其他操作,因此直接調用它可能是個壞主意。if ([foo respondsToSelector:@selector(bar)])
[foo performSelector:@selector(bar))];
用於一般用途(方法有返回值和任意數量的參數),使用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.
}
權的話,只有'performSelector:','performSelector:withObject:'和'performSelector :withObject:withObject:' - 超過2個參數,它不再是一個可行的選擇。我認爲NextSTEP曾經有一個'performv:'允許變量參數,或者類似的東西,但我不太確定... – ephemient 2009-10-30 19:25:50
當你使用NSInvocation或者切換到使用字典作爲論據。這並不難,只需要幾個電話。 – 2009-10-30 20:04:25
另外,1.如果參數類型都是對象而且返回類型是對象或空 – user102008 2012-05-11 19:17:40