繁体   English   中英

符合Objective-C协议的Swift类

[英]Swift class conforming to Objective-C protocol

在Objective-C中,我具有以下协议

@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编写的Google演示项目时,一切都会100%地起作用。 由于最后一部分,我假设网络或硬件或类似的东西都没有问题。

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

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

尝试:

class ViewController: UIViewController, GCKDeviceScannerListener {

    var deviceScanner = GCKDeviceScanner()

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

苹果公司关于协议的文档既漫长又复杂。

最容易想到的是诸如可选闭包之类的optional协议方法,并且可以将其与可选链接一起使用。

@objc class Something {
    var delegate: GCKDeviceScannerListener?

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM