从扩展中调用委托方法会抛出nill,但在操作事件上有效

时间:2019-07-06 11:26:13

标签: ios swift delegates extension-methods swift4.2

下面是代码段,当定期delegate方法被调用时,XMPPStreamDelegate永远不会调用。状态服务delegate在扩展名内抛出nil,但在从另一个视图控制器调用某些操作时却提供了价值。

public protocol PresenceServiceDelegate{
    func didPresenceReceive()
}

class PresenceService: NSObject{ 
    var delegate: PresenceServiceDelegate?

    public override init()
        delegate = self
     }
}

extension PresenceService: XMPPStreamDelegate {

    public func didReceive presence() // XMPPStrem delegate

        // My Presence Service delegate not at all calling (delegate throws nil )
        delegate?.didPresenceReceive()
    }
}


class ViewController: UIViewController{
    var presence = PresenceService()

    func viewDidLoad() {
        presence.delegate = self
    }
}

extension ViewController: PresenceServiceDelegate {
    public func didPresenceReceive(){
        print("test")
    }
}

1 个答案:

答案 0 :(得分:0)

以下代码可以正常工作。在XMPPStreamDelegate调用过程中,presenceservice委托对象抛出nill且未被识别,这里下面的代码调用了presentationservice的类的实例,该实例启用了它自己的委托实例并按预期触发了视图控制器的值。

class PresenceService: NSObject{ 
    var delegate: PresenceServiceDelegate?

     public override init()
        delegate = self
     }

    // Singleton instance
    public class var sharedInstance : PresenceService {
        struct PresenceServiceInstance {
            static let instance = PresenceService()
        }
        return PresenceServiceInstance.instance
    }
}

extension PresenceService: XMPPStreamDelegate {

    public func didReceive presence() // XMPPStrem delegate

        // My Presence Service delegate not at all calling (delegate throws nil )
        PresenceServiceInstance.sharedInstance.delegate?.didPresenceReceive()
    }
}