Avoid Retain Objects When Using Static Var Swift 5

Welcome to my new article, I've just learned about memory in iOS.  It's actually not hard to understand because of ARC (Automatic Reference Counting) that helps a lot about handling memory. But you need to handle a few conditions that ARC can't handle. It usually uses "weak" syantax. It tells to memory that It is not strong pointer. It's literally variable that is used "weak" can be nil.

"weak self" and "unowned self" helps us when we use closure and try to self inside it. It will make iOS can handle better your apps. Use "weak self" if self could be nil and Use "unowned self" if self will be never nil. It's actually confusing for the first time we have heard the theory. So we need to practice it to make it perfect.

But what I actually concern is when we use static var in enum or struct. And I try to access it in view controller or other classes. It will make class or view controller doesn't run deinit which is we need to know our view controller is discarded and it makes our memory cannot be leak. So How do we solve it ? It simply like we have talked before. We need to use "weak" syntax before "static var". So the memory will discard it when no one points to variable. I will give example below, don't worry.

So I have a view controller and I have an enum that contains constant variable. "weak" works even you use static let. So it doesn't just work for var only but it also works for static let. You can try demo above and try it, deinit is called when view controller is deallocated from memory space. For "weak self" is usually used when your closure use UI like click button and "unowned self" is usually used when your closure fetch data from network.

That's all guys. I apologize if my grammar is not good. I still learned how to write english correctly. If you have any question, feel free to ask. I'm glad to help ya all. Thanks for visiting my simple blog. Have a nice day.

Popular posts from this blog

Missing system image Android Studio solution

How to restart the app with flutter Android and iOS

How to get thumbnail from video URL in Swift 5