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!!!

Sign up to discover human stories that deepen your understanding of the world.

Free

Distraction-free reading. No ads.

Organize your knowledge with lists and highlights.

Tell your story. Find your audience.

Membership

Read member-only stories

Support writers you read most

Earn money for your writing

Listen to audio narrations

Read offline with the Medium app

--

--

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

Write a response