How does memory release occur for objects created using reference types?
sobes.tech AI
Answer from AI
In iOS, objects created using reference types (such as classes in Swift or Objective-C) are managed by the reference counting system (ARC — Automatic Reference Counting). Each object maintains a reference count — the number of active references to it. When a new reference to an object is created, the count increases, and when a reference is no longer used (for example, a variable goes out of scope or is assigned nil), the count decreases.
When the reference count of an object reaches zero, it means no one is referencing it anymore, and the memory occupied by the object is automatically released. This helps prevent memory leaks without manual management.
Example in Swift:
class Person {
var name: String
init(name: String) {
self.name = name
}
deinit {
print("Person \(name) released")
}
}
var p1: Person? = Person(name: "Ivan")
var p2 = p1 // reference count increased
p1 = nil // reference count decreased, but object still exists
p2 = nil // reference count becomes 0, object is released
It is important to avoid retain cycles, where two objects reference each other, preventing memory from being released. To do this, weak or unowned references are used.