【问题标题】:Swift class conforming to Objective-C protocol符合 Objective-C 协议的 Swift 类
【发布时间】:2015-02-05 10:36:59
【问题描述】:

在 Objective-C 中我有 the following protocol:

@protocol GCKDeviceScannerListener <NSObject>    
@optional

- (void)deviceDidComeOnline:(GCKDevice *)device;
- (void)deviceDidGoOffline:(GCKDevice *)device;
- (void)deviceDidChange:(GCKDevice *)device;

@end

当试图在 Swift Xcode 6.1 中遵循这个协议时,它会像这样自动完成:

class ViewController: UIViewController, GCKDeviceScannerListener {

    override func viewDidLoad() {
        super.viewDidLoad()
        var deviceScanner = GCKDeviceScanner();
        deviceScanner.addListener(self);
        deviceScanner.startScan();
        println("scanning");
    }

    func deviceDidComeOnline(device: GCKDevice!) {
        println("deviceDidComeOnline()");
    }

    func deviceDidGoOffline(device: GCKDevice!) {
        println("deviceDidGoOffline()");
    }

    func deviceDidChange(device: GCKDevice!) {
        println("deviceDidChange()");
    }

}

代码在模拟器上编译并且看起来运行正常。但是,从未触发任何侦听器函数。运行仅用 Objective-C 编写的the demo project from Google 时,一切都 100% 有效。由于最后一部分,我假设网络或硬件或类似的东西没有任何问题。

可能是我错过了https://developers.google.com/cast/docs/ios_sender 的重要内容,但我想知道根据协议,Swift 代码本身是否正确。由于该协议只有可选功能,因此很难知道它是否正确。

【问题讨论】:

  • 你可以使用self.respondsToSelector("deviceDidComeOnline:")来测试你的ViewController的协议一致性

标签: ios objective-c swift chromecast


【解决方案1】:

Apple's documentation on Protocols 又长又复杂。

最容易想到 optional 协议方法,如可选闭包,您可以将它与可选链一起使用。

@objc class Something {
    var delegate: GCKDeviceScannerListener?

    func someCallback() {
        delegate?.deviceDidComeOnline?(device)
    }
}

【讨论】:

  • 我不认为这是 OP 要求的
【解决方案2】:

我没有使用此库的经验,但我认为您应该保留对 GCKDeviceScanner 的引用。

试试:

class ViewController: UIViewController, GCKDeviceScannerListener {

    var deviceScanner = GCKDeviceScanner()

    override func viewDidLoad() {
        super.viewDidLoad()
        deviceScanner.addListener(self)
        deviceScanner.startScan()
        println("scanning")
    }

【讨论】:

  • 我打算否决您的答案,因为我认为这与我的问题无关,但后来我查看了您的 SO 分数,然后尝试了一下,它奏效了。 :) 你知道或愿意评论它为什么会这样吗?
  • 在您的原始代码中,deviceScannerviewDidLoad 返回时被释放。我认为,这会默默地取消扫描,并删除其侦听器。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2015-04-27
  • 1970-01-01
  • 1970-01-01
  • 2015-09-04
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多