atr*_*bbi 5 objective-c ios swift
我正试图在swift中从Objective-C实现这个可选的协议方法:
- (void)customHTTPProtocol:(CustomHTTPProtocol *)protocol logWithFormat:
(NSString *)format arguments:(va_list)arguments;
Run Code Online (Sandbox Code Playgroud)
(cfr:https://developer.apple.com/library/ios/samplecode/CustomHTTPProtocol/Introduction/Intro.html)我在swift中编写了这个方法:
func customHTTPProtocol(`protocol`: CustomHTTPProtocol!, logWithFormat format: String!, arguments: CVaListPointer) {
}
Run Code Online (Sandbox Code Playgroud)
它抱怨不能满足可选要求并建议在方法之前添加@objc,但是如果我添加@objc它会给出错误(CVaListPointer不能在Objective-C中表示)
问题是这个测试失败了:
if ([strongDelegate respondsToSelector:@selector(customHTTPProtocol:logWithFormat:arguments:)]) {
Run Code Online (Sandbox Code Playgroud)
而且没有调用swift方法
如果你想@protocol在 swift 类中使用 Objective-C,那么你必须将 Objective-C 类导入到你的桥接头文件中,该文件是当你在 Swift 项目中使用 Objective-C 文件时由 XCode 创建的。那么显然你必须在 swift 文件中添加委托,你必须像这样使用它。
class classname : baseClass<yourDelegate> {
}
Run Code Online (Sandbox Code Playgroud)
首先,您必须在此文件中添加所有必需的委托方法,然后添加您必须使用的可选方法。如果您不添加所需的委托方法,则会出现错误。
但是,如果你想从 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> {
}
Run Code Online (Sandbox Code Playgroud)
然后将你的 swift 类导入到你的 Objective-C 文件中,如下所示,
#import <PROJ_NAME/PROJ_DIR-Swift.h>
Run Code Online (Sandbox Code Playgroud)
重要的是要添加:
classObj.delegate = self
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
444 次 |
| 最近记录: |