使用Singleton不调用Delegate方法

时间:2017-11-06 08:33:48

标签: delegates singleton protocols ios11 swift4

已经提出了类似的问题,但它们没有帮助。我试图从视图控制器调用Singleton类中声明的协议方法,但被调用的方法永远不会调用。

我的协议和课程是:

import Foundation

protocol ServiceDelegate {
  func serviceData(data: [String: Any])
}

class Service {

private static let sharedInstance = Service()  // singleton object
var delegate: ServiceDelegate?

class func shared() -> Service {
    return sharedInstance
}

func login(postData:String) {

    let url = URL(string: "MY_URL")!
    var request = URLRequest(url: url)
    request.httpMethod = "POST"
    request.setValue("application/x-www-form-urlencoded", forHTTPHeaderField: "Content-Type")
    let dataBody = postData.data(using:String.Encoding.ascii, allowLossyConversion: false)
    request.httpBody = dataBody
    let task = URLSession.shared.dataTask(with: request) { (data, response, error) in
        guard let data = data, error == nil else {
            print(error?.localizedDescription ?? "No data")
            return
        }
        let responseJSON = try? JSONSerialization.jsonObject(with: data, options: [])
        if let dataArray = responseJSON as? [String: Any] {
            self.delegate?.serviceData(data: dataArray)   // This is getting called
        }
    }
    task.resume()
  }
}

我实现协议的视图控制器类是:

import UIKit

class LoginVC: UIViewController, ServiceDelegate {

var serviceInstance: Service = Service()

override func viewDidLoad() {
    super.viewDidLoad()
    serviceInstance.delegate = self
}

@IBAction func loginBtn(_ sender: Any) {
    let info = "userName=\(String(describing: usernameText.text!))&password=\(String(describing: passwordText.text!))"
    Service.shared().login(postData: info)
}

// This is not getting called:
func serviceData(data: [String : Any]) {
    print(data)
}

上述实施是否正确?我可以使用私有单例对象来成功实现协议方法吗?

1 个答案:

答案 0 :(得分:0)

您正在创建两个 Service个实例。您应该只使用Service.shared()返回的那个。这是您的应用中共享的实际单身

在视图控制器中,替换此行:

serviceInstance.delegate = self

使用:

Service.shared().delegate = self

你还应该删除这一行(即不必要的第二个实例):

var serviceInstance: Service = Service()