【问题标题】:Objective-C protocol method invisible in SwiftObjective-C 协议方法在 Swift 中不可见
【发布时间】:2015-10-27 10:05:20
【问题描述】:

我目前正在我的ObjC 项目中处理一些 Swift 类。

我遇到的问题如下:

我在 ClassA.h 中声明了这个协议:

@protocol MyProtocol <NSObject>
    - (void)complexMethodWithArg1:(id)arg1 arg2:(id)arg2 arg3:(id)arg3;
    - (Folder *)currentDestinationFolder;
    - (Flow)currentFlow;
@end

相当标准的东西。

现在我的目标是创建一个带有属性的 swift 类,该属性是实现此协议的对象。 所以很自然地,我将我的类添加到 swift 桥接头:

//
//  Use this file to import your target's public headers that you would like to expose to Swift.
//

#import "ClassA.h"

并在 ClassB 下的 swift 文件中声明我的属性,这是一个实现另一个协议的 UIViewController

class ClassB : UIViewController, AnotherProtocol {

    var delegate:MyProtocol?

}

这里的问题是:我想在viewDidLoad 中调用一堆我的委托方法。它适用于所有这些方法,除了一种不会自动完成并且手动输入时会出错的方法:

override func viewDidLoad() {
    self.delegate?.currentDestinationFolder() // works great, no problem
    self.delegate?.currentFlow() // works great, no problem
    self.delegate?.complexMethodWithArg1(arg1: arg1, arg2: arg2, arg3: arg3) // PROBLEM : no autocompletion, error if entered manually ! 

    super.viewDidLoad()
}

我不知道发生了什么,它与可选或必需的协议方法无关,与我的委托属性是可选的(尝试解包)这一事实无关。

有人遇到过类似的问题吗?似乎是某种错误?

【问题讨论】:

  • self.delegate?.complexMethodWithArg1 没有完全声明
  • @baydi 是的,我知道,这只是为了表明没有自动完成功能。它也完全声明失败。
  • 可能应该是:- (void)complexMethodWithArg1:(id)arg1 arg2:(id)arg2 arg3:(id)arg3;?
  • 是的,感谢您指出这一点,只是一个错字,我不允许显示实际代码。
  • 试试self.delegate?.complexMethodWithArg1(arg1, arg2: arg2, arg3: arg3)self.delegate?.complexMethodWith(arg1: arg1, arg2: arg2, arg3: arg3)

标签: ios objective-c swift protocols bridging-header


【解决方案1】:

我继续尝试在一个空项目上重现该问题。

MyProtocol.h(从您的问题和 cmets 中获取声明)

@import Foundation;
@import UIKit;

@class CAPNavigationBar;

@protocol MyProtocol <NSObject>

- (void)setupNavigationItemInNavigationBar:(CAPNavigationBar *)navigationBar
                            navigationItem:(UINavigationItem *)navigationItem
                          inViewController:(UIViewController *)viewController;

@end

CAPNavigationBar.h(只是一个模拟)

@import Foundation;

@interface CAPNavigationBar : NSObject

@end

ViewController.swift

import UIKit

class ViewController: UIViewController {
    var delegate: MyProtocol?

    override func viewDidLoad() {
        super.viewDidLoad()

        let capNavigationBar = CAPNavigationBar()

        self.delegate?.setupNavigationItemInNavigationBar(capNavigationBar, navigationItem: nil, inViewController: self)
    }
}

桥接头

#import "MyProtocol.h"
#import "CAPNavigationBar.h"

总结

一切都按预期进行。

你要么有一个简单的拼写错误,要么你没有正确地将所有类型导入到 Swift 中。尤其要确保您不只是将类型作为前向声明导入。

【讨论】:

  • 该死的,就是这样!我的网桥中没有#import "CAPNavigationBar.h"。我猜桥无法创建该方法,因为 swift 不知道协议方法中的一种参数类型。非常感谢!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2018-05-16
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-12-15
  • 2015-01-01
相关资源
最近更新 更多