Ferrakkem Bhuiyan
Ferrakkem Bhuiyan

Reputation: 2783

Delegate not get called

protocol WeatherManagerDelegate {
    func didUpdateWeater(weather: ConsolidatedWeather)
    func didFailWithError(error: Error)
}

ViewController: where i am setting value didSelectRowAt and using performSegue going to another viewController

   class WeatherListViewController: UIViewController {
            var delegate: WeatherManagerDelegate?

    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
            let index = weatherViewModel.didSelect(at: indexPath.row)
            self.delegate?.didUpdateWeater(weather: index)
            performSegue(withIdentifier: K.DetailsView.segueIndentifier, sender: self)
        }
        
        override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
            let destinationVc = segue.destination as! DetailsViewController
            
        }
    
    }

this is my ViewModel calss: from my ViewModel, I will send value to ViewController and Update UI

class DetailsWeatherViewModel{
    
    var  w = WeatherListViewController()
    
    func a(){
        print("aaa")
        w.delegate = self
    }
}


extension DetailsWeatherViewModel: WeatherManagerDelegate{
    func didUpdateWeater(weather: ConsolidatedWeather) {
        weatherData = weather
        print("weatherData: \(String(describing: weatherData))")
    }
    
    func didFailWithError(error: Error) {
        print(error)
    }
}

what I am doing wrong...????

Upvotes: 0

Views: 58

Answers (2)

Deepa Bhat
Deepa Bhat

Reputation: 214

If you are following MVVM architecture then you can create a viewModel object inside your viewcontroller and then use the updated values in VM directly using VM object. Else if you want to use delegate then you need to write the protocols in viewModel and use it in VC. You shouldn't be creating Viewcontroller object inside the Viewmodel.

Upvotes: 0

Jaekyung You
Jaekyung You

Reputation: 33

You should be careful of memory leaks when using delegate pattern. I think you can solve this problem by making protocol limit to class and declare property by weak var. Although WeatherListViewController disappeared, WeatherListViewController and DetailsWeatherViewModel are not likely to be deinit unless you use weak reference. Try this.

protocol WeatherManagerDelegate : class {
    func didUpdateWeater(weather: ConsolidatedWeather)
    func didFailWithError(error: Error)
}
weak var delegate: WeatherManagerDelegate?

Upvotes: 1

Related Questions