Home > Net >  MVVM: binding the View with the ViewModel with closures, how that results in retain cycle?
MVVM: binding the View with the ViewModel with closures, how that results in retain cycle?

Time:10-07

I'm implementing a simple ItemListing app where the ProductList viewController manages a table view which shows the results of a call to a REST service. The Detail viewController manages a view where I show more information about the item selected in the ProductListVC. I'm trying to apply MVVM pattern. I am using closures for the binding between view model and View controller. In the ProductList viewController, I create and initialize its viewModel this way:

class ProductListVC: UIViewController {
    var viewModel: ProductViewModel = ProductViewModel()
    var productTblView = UITableView()
    
    override func viewDidLoad() {
        super.viewDidLoad()
    
        initViewModel()
    }
    
    func initViewModel() {
        viewModel.reloadTableViewClosure = { [weak self] () in
            DispatchQueue.main.async {
                self?.productTblView.reloadData()
            }
        }
    
        viewModel.fetchData()
    }
}

My question is what is the need of using [weak self] in reloadTableViewClosure? How the strong reference happens in this case? It would be great if anybody can explain the usage of [weak self] or [unowned self] in this case. My confusion is, since the reloadTableViewClosure is owned by viewmodel how self maintains strong reference to closure?

CodePudding user response:

Here [weak self] used for your productTblView, not for viewModel. "self" is specifying here for ProductListVC. Suppose the controller object has been deallocated and then we update strongly productTblView. It will cause a crash so we use [weak self]/[unowned self].

CodePudding user response:

Unowned reference can’t be nil and Weak can. see the reference https://medium.com/@kiran.jasvanee/difference-between-unowned-self-and-weak-self-in-swift-310c14961953

https://www.avanderlee.com/swift/weak-self/

  • Related