【问题标题】:Implement objectivec protocol in swift快速实现objectivec协议
【发布时间】:2015-11-17 07:28:40
【问题描述】:

我正在尝试在 swift 中从 Objective-C 实现这个可选协议方法:

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

(参见: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方法

【问题讨论】:

    标签: ios objective-c swift


    【解决方案1】:

    如果你想在 swift 类中使用objective-c @protocol,那么你必须将objective-c 类导入到你在swift 项目中使用objective-c 文件时由XCode 创建的Bridging-Header 文件中。然后显然你必须在你必须使用它的 swift 文件中添加委托。

    class classname : baseClass<yourDelegate> {
    
    }
    

    首先你必须在这个文件中添加所有必需的委托方法,然后添加你必须使用的可选方法。如果你没有添加所需的委托方法,那么它会给你错误。

    但是,如果您想在 swift 中使用 protocol 到 Objective-c,那么您必须在 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
    

    【讨论】:

    • 这已经完成了,我还有一个问题,由于协议方法是可选的,并且 (va_list) 可能翻译错误
    猜你喜欢
    • 1970-01-01
    • 2014-09-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多