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.
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()
}
}
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()
}
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With