What Is The ARC -Swift
// Tip From WriterIf you did not learn "Git-Github", it is a big mistake. I recommend you to at least read the documentations about it now!
Automatic Reference Counting (ARC) when we create an instance, ARC allocates a chunk of memory for us until these instances haven’t strong references which means when these instances reference count on Heap if equal to zero deallocating from Heap.
Reference counts , determine when an object is no longer needed. The object is no longer needed when its usage count reaches zero.
Value Types stored on Stack area. So they don’t have a reference count. ARC working on the Heap area.
Initialization and deallocation statements both appear. These statements show that you have deallocated the object at the end.
Usually, we don”t worry about memory leaks. ARC handles for us. But sometimes ARC is confusing because as I mentioned above, the reference count is never equaling zero and that is creating a memory leak on our App that is called Reference Cycles / Strong Cycles. When is that happening? and what is the solution for it? To see a strong cycle, we must add more code.
Add those codes:
Deinit block did not activate as you see on the result. That means the reference count will not equal zero. It is happening when the reference count is not zero(when we create a strong cycle) So our app will be memory leaking all the time. On row 22 owner property is creating a strong cycle. Unless otherwise specified, all references are strong. How to fix that?
For break strong reference cycles, we can specify the relationship between property objects as weak or unowned.
What are mean Strong, Weak, or Unowned References?
Strong Reference — This is the default reference type. When we assign the class instance to a variable, constant that creates a strong reference.
Strong reference doesn’t allow instance to be deallocated for as long as that reference count is not equal to zero.
Weak Reference — Weak references don’t participate in the lifecycle management of an object. That means when the reference count goes to zero, the reference can automatically be set to nil.
In our sample, we need to change row 22 like that.
weak var owner: User?
Let's see the result :
Yes! We successfully fixed the memory leak.
Unowned Reference — Last reference modifier we can use that doesn’t increase the reference count.
What’s the difference between unowned
and weak
?
A weak reference is always optional and automatically becomes nil
when the referenced object goes away.
Unowned references, by contrast, are never optional types. If you try to access an unowned property that refers to a deinitialized object, you’ll trigger a runtime error comparable to force unwrapping a nil optional type.
I hope this article was helpful.
References :