简体   繁体   English

符合Objective-C协议的Swift类

[英]Swift class conforming to Objective-C protocol

In Objective-C I have the the following protocol : 在Objective-C中,我具有以下协议

@protocol GCKDeviceScannerListener <NSObject>    
@optional

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

@end

When trying to conform to this protocol in Swift Xcode 6.1 autocompletes it like this: 在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()");
    }

}

The code compiles and seemingly runs ok on the simulator. 该代码可以编译,并且看起来可以在模拟器上正常运行。 However, none of the listener functions are ever triggered. 但是,没有触发任何侦听器功能。 Everything works 100% of the time when running the demo project from Google written in Objective-C only. 仅运行 Objective-C编写的Google演示项目时,一切都会100%地起作用。 Because of the last part I'm assuming that the there aren't any problems with the network or hardware or anything like that. 由于最后一部分,我假设网络或硬件或类似的东西都没有问题。

It could be that I have missed something important from https://developers.google.com/cast/docs/ios_sender , but I would like to know if the Swift code itself is correct according to the protocol . 可能是因为我错过了https://developers.google.com/cast/docs/ios_sender中的重要内容,但是我想知道Swift代码本身根据协议是否正确 As the protocol only has optional functions it's hard to know if it's right. 由于该协议仅具有可选功能,因此很难知道它是否正确。

I have no experience with this library, but I think you should keep the reference to GCKDeviceScanner . 我没有使用此库的经验,但是我认为您应该保留对GCKDeviceScanner的引用。

Try: 尝试:

class ViewController: UIViewController, GCKDeviceScannerListener {

    var deviceScanner = GCKDeviceScanner()

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

Apple's documentation on Protocols is long and complex. 苹果公司关于协议的文档既漫长又复杂。

It's easiest to think of optional protocol methods like Optional closures, and you can use it with optional chaining. 最容易想到的是诸如可选闭包之类的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