Delegating Objective-C Protocol on Swift

こ雲淡風輕ζ 提交于 2020-02-03 08:40:31

问题


I'm implementing an UDP Listener on iOS using the Swift language.

For this I'm relaying on the CocoaAsyncSocket project.

I was succeeded on importing the CocoaAsyncSocket library using a Bridging-Header.h, I could call the functions from the Objective-C classes, but I'm not able to write the delegate function on swift.

This is the code where I set the Socket and define the ViewController.swif as the delegate class for the listener:

func setupSocket() {
    var udpSocket : GCDAsyncUdpSocket = GCDAsyncUdpSocket(delegate: self, delegateQueue: dispatch_get_main_queue())
    var error : NSError?
    let port : UInt16 = 12121
    let address : String = "228.5.12.12"
    udpSocket.bindToPort(port, error: &error)
    udpSocket.joinMulticastGroup(address, error: &error)
    udpSocket.enableBroadcast(true, error: &error)
    println("228.5.12.12")
}

This is the former delegate function in Objective-C:

- (void)udpSocket:(GCDAsyncUdpSocket *)sock didReceiveData:(NSData *)data
                                               fromAddress:(NSData *)address
                                         withFilterContext:(id)filterContext;

And finally, this is how I'm implementing the function on Swift:

override func udpSocket(sock : GCDAsyncUdpSocket!, didReceiveData data : NSData!,  fromAddress address : NSData!,  withFilterContext filterContext : AnyObject!) {
    println(data)
}

ViewController class is declared to implement the right protocol:

class ViewController: UIViewController, GCDAsyncUdpSocketDelegate {
    ...
}

I got no compile error except for the override.

Question: What am I doing wrong?


回答1:


override keyword is for overriding methods of superclass. As you are not overriding any methods, override keyword is not needed.




回答2:


There are two possibilities for your delegate method not getting called.

1) I did not see in the code snippet where you set the delegate on the udpSocket variable

2) ARC probably will also come into play, and the GCDAsyncUdpSocket object instance you created will have already had it's memory released.

If you declare the variable for the socket to be a local variable inside the setupSocket function, once the function finishes the reference count on the object is 0. Making it an variable of the class will fix that problem.

Also the override keyword should be removed, as that is only used if overriding a method in the base class.

var udpSocket: GCDAsyncUdpSocket!

func setupSocket() 
{
    udpSocket = GCDAsyncUdpSocket(delegate: self, delegateQueue: dispatch_get_main_queue())

    if (udpSocket == nil)
    {
       // Should display an error here
       return
    }

    // Set delegate 
    udpSocket.delegate = self
    // Other code that you had
}


来源:https://stackoverflow.com/questions/24699567/delegating-objective-c-protocol-on-swift

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!