簡體   English   中英

Objective-C va_list和選擇器

[英]Objective-C va_list and selectors

是否可以使用@selectorperformSelector:或類似)與使用變量參數列表的方法?

我正在編寫一個可以分配委托的類來覆蓋默認行為。 在存在委托select方法的情況下,對該類的實例進行的調用將轉發到相同的相應委托方法,其中一些方法使用變量參數列表。

因此,例如,我需要能夠創建檢索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];

我只是想知道我是否遺漏了一些東西,或者想要實現我想要的目標?

您可以將任何想要的內容傳遞給運行時函數objc_msgSend

objc_msgSend(del, @selector(logEventWithFormat:arguments:), format, argList);

這是發送手動構造的消息的最有效方式。

但是,您不清楚是否需要以這種方式執行調用。 正如KennyTM指出的那樣,在您擁有的代碼中,您可以直接調用該方法。

您不能使用-performSelector:withObject:withObject:因為va_list根本不是“對象”。 您需要使用NSInvocation

或者直接打電話

[del logEventWithFormat:format arguments:argList];

據我所知,它無法完成。 你不能使用-performSelector:withObject:withObject:因為@KennyTM指出, va_list不是一個對象。

但是,您也無法使用NSInvocation 直截了當的文件說:

NSInvocation不支持使用可變數量的參數或聯合參數調用方法。

由於這兩種方式是通過選擇器調用方法,並且似乎都不起作用,我將繼續使用“無法完成”的答案,除非您直接調用該方法並將va_list作為參數傳遞。

也許@bbum會出現並進一步啟發我們。 =)

我之前沒有這樣做,但我經常使用的簡單解決方案是為withObject參數打包/取消裝入NSMutableArray或NSMutableDictionary。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM