如何在init函数中将委托设置为self?

7

我有一个名为MQTTController的类,其中包含共享实例和一个私有的初始化方法。

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()
    } 
}

我知道可以创建另一个方法来设置代理并调用mqtt.connect(),但我想知道是否有其他解决方案,不必创建和调用另一个方法。

2个回答

6
错误信息告诉你需要做什么,你需要在init函数中调用super.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()
    } 
}

4

您也可以使用defer,但建议使用super.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

        defer {
            mqtt.delegate = self
            mqtt.connect()
        }
    } 
}

感谢提供另一种选择。 - Varun Naharia

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接