omi23
omi23

Reputation: 116

Delegate method not called properly

I am using a Service class where a protocol is declared. This protocol is implemented by two viewcontrollers, i.e. DashboardVC and DashboardDetailVC. Protocol works fine when called from DashboardVC. Then in DashboardDetailVC also, it works fine calling protocol method defined in DashboardDetailVC. BUT, when I dismiss DashboardDetailVC and move back to DashboardVC, then protocol method of DashboardDetailVC is called. My code is:

Service.swift

protocol DashboardDelegate {
  func dashboardInfoResponse(data: [String: Any])
}

class Service {
  var dashboardDelegate: DashboardDelegate?

  func hitWebRequest(api: String, request: URLRequest) {
    ..
    self.dashboardDelegate?.dashboardInfoResponse(data: dataArray)
    ..
  }
}

DashboardVC.swift

class DashboardVC: DashboardDelegate {

override func viewDidLoad() {
    super.viewDidLoad()
    Service.shared().dashboardDelegate = self
}

override func viewWillAppear(_ animated: Bool) {
    super.viewWillAppear(true)

    Service.shared().dashboardInfo(postData: token)

}

func dashboardInfoResponse(data: [String : Any]) {
  ..
  ..
}

DashboardDetailVC.swift

class DashboardDetailVC: DashboardDelegate {

override func viewDidLoad() {
    super.viewDidLoad()
    Service.shared().dashboardDelegate = self
}

override func viewWillAppear(_ animated: Bool) {
    super.viewWillAppear(true)

    Service.shared().dashboardInfo(postData: token)

}

func dashboardInfoResponse(data: [String : Any]) {
  ..
  ..
}

When I go back from DashboardDetailVC to DashboardVC using

dismiss(animated: true, completion: nil)

protocol method from DashboardVC is called, But still it returns to dashboardInfoResponse protocol method in DashboardDetailVC.

Upvotes: 1

Views: 304

Answers (2)

Erhan Demirci
Erhan Demirci

Reputation: 4209

if you override viewWillAppear , yourView.delegate=self not work for that. you have to identify your .delegate=self on override method

Upvotes: -1

Prashant Tukadiya
Prashant Tukadiya

Reputation: 16466

This is obvious You have class Service which has sharedInstance that means only single object is been used in whole application cycle.. And only single delegate property been shared among all.

Observe that

DashboardVC in viewDidLoad you set delegate to self that means it is pointing to DashboardVC

After that you present DashboardDetailVC you set delegate to self that means it is pointing to DashboardDetailVC

and after that your all delegate call will go to DashboardDetailVC not to DashboardVC even though you dismiss VC

To fix this: You have options.

1) Don't use Shared Instance

2) set delegate in ViewWillAppear instead.

3) Use NotificationCenter and post notification

Hope it is helpful to you

Upvotes: 2

Related Questions