是否可以使用@selector
和performSelector:
(或類似的)與使用可變參數列表的方法?Objective-C va_list和選擇器
我在寫一個可以分配委託來覆蓋默認行爲的類。在存在委託選擇方法的情況下,對該類的實例進行的調用將轉發給相同的相應委託方法,其中一些使用可變參數列表。
所以,舉例來說,我需要能夠創建檢索SEL
參考和消息的方法中的委託對象像這樣:
- (void)logEventWithFormat:(NSString *)format, ... {
va_list argList;
id del = self.delegate;
if (del != nil &&
[del conformsToProtocol:@protocol(AProtocolWithOptionalMethods)] &&
[del respondsToSelector:@selector(logEventWithFormat:)])
{
// Perform selector on object 'del' with 'argList'
}
}
我假定這是不可能的,因此,類似的方法聲明Foundation框架 - 在NSString
:
- (id)initWithFormat:(NSString*)format, ...;
和
- (id)initWithFormat:(NSString *)format arguments:(va_list)argList;
我假設我希望協議委託給應建議的落實:
- (void)logEventWithFormat:(NSString *)format arguments:(va_list)argList;
所以我選擇@selector(logEventWithFormat:arguments:)
可以使用調用:
[del performSelector:@selector(logEventWithFormat:arguments:)
withObject:format
withObject:argList];
我,如果我想知道錯過了什麼或者走了很長的路要實現我想要的?
'NSInvocation'不起作用。文件說明如此。 – 2010-01-26 07:03:00
@Dave:如果您將'va_list'作爲參數傳遞('ObjC運行時「中的'va_list'等價於'void *'),'NSInvocation' *將會工作。你不能將任意多個參數傳遞給'-stringWithFormat:'帶'NSInvocation',因爲類型簽名省略了'...'部分。 – kennytm 2010-01-26 07:13:55