簡體   English   中英

在swift中實現objectivec協議

[英]Implement objectivec protocol in swift

我正試圖在swift中從Objective-C實現這個可選的協議方法:

- (void)customHTTPProtocol:(CustomHTTPProtocol *)protocol logWithFormat:
(NSString *)format arguments:(va_list)arguments;

(cfr: https//developer.apple.com/library/ios/samplecode/CustomHTTPProtocol/Introduction/Intro.html )我在swift中編寫了這個方法:

func customHTTPProtocol(`protocol`: CustomHTTPProtocol!, logWithFormat format: String!, arguments: CVaListPointer) {
}

它抱怨不能滿足可選要求並建議在方法之前添加@objc,但是如果我添加@objc它會給出錯誤(CVaListPointer不能在Objective-C中表示)

問題是這個測試失敗了:

if ([strongDelegate respondsToSelector:@selector(customHTTPProtocol:logWithFormat:arguments:)]) {

而且沒有調用swift方法

如果你想在swift類中使用objective-c @protocol ,那么在你的swift項目中使用objective-c文件時,你將導入objective-c類放入你的Bridging-Header文件中,該文件是由XCode創建的。 那么顯然你必須在swift文件中添加委托,你必須使用它。

class classname : baseClass<yourDelegate> {

}

首先,在此文件中,您必須添加所有必需的委托方法,然后添加必須使用的可選方法。 如果您不添加所需的委托方法,那么它會給您錯誤。

但是如果你想使用從swift到objective-c的protocol ,那么你必須在protocol名稱之前添加@objc並將swift文件導入到objective-c文件中,你還要在類之前添加@objc,

@objc protocol DelegateName {
    //declare your required and optional delegate method here
}

@objc classname : baseClass<yourDelegate> {

}

然后將你的swift類導入到你的objective-c文件中,

#import <PROJ_NAME/PROJ_DIR-Swift.h>

而且重要的是要添加:

classObj.delegate = self

暫無
暫無

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

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