简体   繁体   中英

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM