Home > Software engineering >  Does closure create a strong reference to an object that is created inside closure scope?
Does closure create a strong reference to an object that is created inside closure scope?

Time:05-29

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)
 }

CodePudding user response:

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.

  • Related