Nerdy Bunz
Nerdy Bunz

Reputation: 7487

Are memory retain cycles impossible in a single-ViewController-app? (Swift / IOS)

I remember from watching CS193P from Stanford University on YouTube (yes, I'm a smart bunz)... that there's this thing called a memory leak or "retain cycle" -- something really bad -- that can happen when you do things like this:

The solution generally seems to be to use the "weak self" reference instead.

I have 104 of these asynchronous self. references in my ViewController which is why I am a little worried.

HOWEVER... this app is a single-page app... and ALL these self. references are pointing to this main ViewController (or one of its permanent sub-views) which is always there, never dismissed, and never "popped from the stack."

My app seems to work fine... and I don't see the total memory usage going haywire or anything... So does that mean I can leave my (ViewController) code as-is in this regard?

Thanks for help!

Upvotes: 1

Views: 368

Answers (1)

Smartcat
Smartcat

Reputation: 2882

Here are two situations where you may regret not fixing your code:

  • If the device runs low on memory when your app is in the background, there are aspects of your view controller and its views that can be deleted. See this (admittedly old, but still interesting) article. This could easily affect your app more significantly in a future iOS version, or maybe even now depending on what your code is doing.

  • Jump 6 months ahead, where you or someone else on your team is borrowing some of your code for another app. You (or they) will likely get burned. Best to just fix the code now. The fixes shouldn't cause a major refactor, but if you find one that does, you could always insert a big warning comment at that line instead.

Upvotes: 1

Related Questions