Read More
Read now

ARC in Swift

Save

ARC, stands for “Automatic Reference Counting”. Its main purpose is to manage app memory management. Its means we do not have to think about memory management. ARC automatically frees the memory which is used by class instance, when the instance is no longer used.

It is applied to the class instance as it is a reference type. It is not applied to Structure or Enumerator as it is a valued type.

ARC automatically manages the memory but sometimes it required more information about our code to manger memory.

Working of ARC

It works in such a way that, every time when a new class instance is created, it allocates a chunk of memory. The memory holds the instance information. When the class instance is no longer in used then ARC free the memory. If ARC has to deallocate the memory whose instance is in use, in that case, you can not access the instance property or method. If you will try to access them in that case your app will crash.

To make sure that this does not occur, ARC tracks the constant, variable, and property referring to the class instance. If at least anyone is in used then ARC does not deallocate the memory. It is possible because of strong references.

Let takes an example

The above class contains the initializer and Deinitializer, the Deinitializer is called when the instance is deallocated.

When the Employee class is initialized then it prints being initialized.

Now, we have created two-variable emp1 and emp2 of Employee? type and it is initially nill. We have assigned these variables with emp. And now when we set it to nil then Arc deallocate this instance.

Note:- In the above example ARC does not deallocate the instance until all the variable strong reference is broken.

i) strong- It is a default reference. When the class instance is assigned to constant or variable then it makes a strong reference.

ii) weak- It is a reference that does not make a stronghold on the reference. Weak reference can be indicated by placing a weak keyword before a property or variable declaration.

When we run the above example we get

iii) unowned – It also does not make a stronghold on the reference. It is indicated by placing an unowned keyword before a property or variable declaration. ARC does not set the value to nil.

When we run the above example we get

Thanks for reading this blog.

You can also check other blogs from here. if you have any issue or suggestion you can leave your query/suggestion in the comment section.

Reference

Swift Doc

. . .

Leave a Comment

Your email address will not be published. Required fields are marked*


Be the first to comment.

css.php

Big thanks to Webkul and his team for helping get Opencart 3.0.3.7 release ready!

Deniel Kerr

Owner and Founder. Opencart

Talk to Sales
Start a Project

    Message Sent!

    If you have more details or questions, you can reply to the received confirmation email.

    Back to Home