Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to set delegate to self inside init function?

I have class named MQTTController with shared instance and a private init method

class MQTTController:NSObject, CocoaMQTTDelegate {
      static let sharedInstance = MQTTController()
      var clientID:String
      var mqtt:CocoaMQTT
      private override init() {
        clientID = "xyz-" + String(ProcessInfo().processIdentifier)
        mqtt = CocoaMQTT(clientID: clientID, host: "mqttcontroller.mqtt.net", port: 1883)
        mqtt.username = "myusername"
        mqtt.password = "mypassword"
        mqtt.willMessage = CocoaMQTTWill(topic: "/will", message: "dieout")
        mqtt.keepAlive = 30
        mqtt.cleanSession = true
        MQTTController.isConnecting = true
        mqtt.delegate = self    //Error at this Line "'self' used before super.init call"
        mqtt.connect()
    } 
}

Here I know that I can create another method to set delegate and call mqtt.connect() but just want to know is there any solution by that I don't have to create and call another method.

like image 988
Varun Naharia Avatar asked Feb 24 '17 07:02

Varun Naharia


2 Answers

The error message told you what needs to be done, you need to call super.init() in your init.

class MQTTController:NSObject, CocoaMQTTDelegate {
    static let sharedInstance = MQTTController()
    var clientID:String
    var mqtt:CocoaMQTT
    private override init() {
        clientID = "xyz-" + String(ProcessInfo().processIdentifier)
        mqtt = CocoaMQTT(clientID: clientID, host: "mqttcontroller.mqtt.net", port: 1883)
        mqtt.username = "myusername"
        mqtt.password = "mypassword"
        mqtt.willMessage = CocoaMQTTWill(topic: "/will", message: "dieout")
        mqtt.keepAlive = 30
        mqtt.cleanSession = true
        MQTTController.isConnecting = true

        super.init() // This line was missing

        mqtt.delegate = self
        mqtt.connect()
    } 
}
like image 188
Gary Makin Avatar answered Nov 20 '22 20:11

Gary Makin


You should also be able to use defer, but go with the super.init() answer

class MQTTController:NSObject, CocoaMQTTDelegate {
    static let sharedInstance = MQTTController()
    var clientID:String
    var mqtt:CocoaMQTT
    private override init() {
        clientID = "xyz-" + String(ProcessInfo().processIdentifier)
        mqtt = CocoaMQTT(clientID: clientID, host: "mqttcontroller.mqtt.net", port: 1883)
        mqtt.username = "myusername"
        mqtt.password = "mypassword"
        mqtt.willMessage = CocoaMQTTWill(topic: "/will", message: "dieout")
        mqtt.keepAlive = 30
        mqtt.cleanSession = true
        MQTTController.isConnecting = true

        defer {
            mqtt.delegate = self
            mqtt.connect()
        }
    } 
}
like image 4
Alistra Avatar answered Nov 20 '22 19:11

Alistra