Search code examples
iosswiftxcodedelegatesprotocols

I cannot able to pass data with using protocol in swift


I have a xibs, in my homeVC, I m passing a viewModel in didselectItem in collectionView's method. After that, I m navigating detailVC and I assign my delegate to self there but I could not my print data

HomeVC

protocol HomeViewControllerDelegate {
func didTappedIndex(viewModel: HomeCollectionViewCellViewModel)}

    func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
    
    let game = games[indexPath.row]

    self.delegate?.didTappedIndex(viewModel: HomeCollectionViewCellViewModel(with: game))
    
    self.tabBarController?.navigationController?.pushViewController(DetailViewController(nibName: "DetailViewController", bundle: nil), animated: true)
    
}

DetailVC

class DetailViewController: UIViewController {

override func viewDidLoad() {
    super.viewDidLoad()

    HomeViewController().delegate = self
}

}

extension DetailViewController: HomeViewControllerDelegate {

func didTappedIndex(viewModel: HomeCollectionViewCellViewModel) {
    print(viewModel.title)
}

}


Solution

  • when you call

    HomeViewController().delegate = self
    

    you are creating a new instance of HomeViewController(). You are probably confusing this instance with one you've created somewhere else. You want to assign the delegate of the correct HomeViewController.

    one option would be to add an instance variable and shared function to the HomeViewController that allows it to keep track of its instance:

    private static var instance: HomeViewController?
    
    internal class func shared() -> HomeViewController {
        guard let currentInstance = instance else {
            instance = HomeViewController()
            return instance!
        }
        return currentInstance
    }
    

    then you can set the delegate in DetailViewController like this:

    HomeViewController.shared().delegate = self
    

    Another option would be to have a Coordinator where you keep track of all view controllers. Then you could pass the DetailViewController the HomeViewController instance.