我有一个单例类,如下面的代码片段所示。
protocol EmpLoginDelegate {
func empLoginSuccess()
func empLoginFailed()
}
class CommunicationModule {
static let sharedInstance = CommunicationModule()
private init() {
}
var empLoginDelegate:EmpLoginDelegate?
func test(){
self.empLoginDelegate?.empLoginSuccess()
}
}
我的委托类显示在下面的代码段中。
extension LoginViewController: EmpLoginDelegate{
func empLoginSuccess(){
wrongAttempts = 0
loginSuccess = true
print("EmpLoginIsSuccess")
performSegue(withIdentifier: "attendanceView", sender: self)
}
func empLoginFailed(){
wrongAttempts = wrongAttempts + 1
userNameTextField.shake(count: 3, for: 0.3, withTranslation: 10)
passwordTextField.shake(count: 3, for: 0.3, withTranslation: 10)
loginSuccess = false
loginAlert(alertTitle: "Invalid Credentials", alertMsg: "Your employee id or password is not correct")
}
}
当我调用测试函数时 emploginSuccess()方法不会被调用。测试功能成功执行,没有任何错误。 我认为问题是 empLoginDelegate 未在我的代码中初始化,所以我尝试了将其初始化为自我的方法,但没有对我有用。有没有其他方法可以在swift3(iOS 10.3.1)中的单例类中使用委托模式。
答案 0 :(得分:1)
我觉得这种方法很好,对我来说这是最好的方法
final class Singleton {
// Can't init is singleton
private init() { }
//MARK: Shared Instance
static let shared: Singleton = Singleton()
}
答案 1 :(得分:1)
确保您正确地与单身人士沟通。要将LoginViewController
的实例设置为empLoginDelegate
,请致电:
CommunicationModule.sharedInstance.empLoginDelegate = self
来自LoginViewController
内的方法。