Sobes.tech
Junior — Middle

How is memory allocation and deallocation handled for reference data types?

sobes.tech AI

Answer from AI

In iOS, for reference types (such as classes), memory is allocated dynamically on the heap. When a class object is created, the system allocates memory for it on the heap and returns a reference to that object.

Memory is freed using Automatic Reference Counting (ARC). Each object maintains a reference count — the number of active references to it. When a new reference is created, the count increases; when a reference is removed or set to nil, the count decreases. When the count reaches zero, the object is automatically removed from memory.

Example:

class Person {
    var name: String
    init(name: String) {
        self.name = name
    }
}

var person1: Person? = Person(name: "Ivan") // reference count = 1
var person2 = person1 // reference count = 2
person1 = nil // reference count = 1
person2 = nil // reference count = 0, Person object is removed from memory

Thus, developers do not need to manually free memory — ARC manages this automatically.

How is memory allocation and deallocation handled for… - sobes.tech