Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Does closure create a strong reference to an object that is created inside closure scope?

In this example, will vm and targetVC get deinitialized? will it cause a memory leak?

loginModule.checkbox.checkboxAction = { [unowned self] in
   let vm = HomeViewModel()
   let targetVC = HomeViewController(viewModel: vm)
   navigationController?.setViewControllers([targetVC], animated: true)
 }

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Neither vm and targetVC are captured, because they’re defined with the closure. They like any ol’ local variable.

  • vm won’t be deinitialized, because the new HomeViewController keeps a reference to it (I’m assuming it’s a strong references, because it wouldn’t make sense otherwise.

  • targetVC probably won’t get deintialized, because navigationController will be holding a reference to it. There is an oddity here though, that the navigationController is optional, so this set will only happen if it’s not nil. It being optional is weird, and probably improper. It should have been unwrapped earlier.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading