Swift ViewModel Memory Leak?

Mario tsai
Apr 15, 2022

--

It’s a true story. It happens by accident.

class VC1 :UIViewController() {  let viewModel = VC1ViewModel()  func callVC2(){     let vc2 = UIViewController()     vc2.onTap = { (value) in         self.viewModel.callMom()  }  deinit(){
print("VC1 dead")
}
}

So, When VC1 dismiss or popup. VC2 and viewModel still in alive.

It prints nothing.

Change callVC2 like this

func callVC2(){    let vc2 = UIViewController()    vc2.onTap = { [weak self] (value) in        self?.viewModel.callMom()}

When VC1 dismiss or popup, Your memory is free!!!

--

--

Mario tsai
Mario tsai

Written by Mario tsai

Major in physical education. Football referee. And high interest in looking the world through the numbers.

No responses yet