Junior — Middle
How is resource management carried out for the Reference data type in the system?
sobes.tech AI
Answer from AI
In iOS, resource management for reference data types (reference types, such as classes) is handled using Automatic Reference Counting (ARC). Each object maintains a reference count, which increases when a new reference to the object is created and decreases when a reference is removed. When the count reaches zero, the object is automatically deallocated from memory.
Example:
class MyClass {
var value: Int
init(value: Int) {
self.value = value
}
}
var obj1: MyClass? = MyClass(value: 10) // reference count = 1
var obj2 = obj1 // reference count = 2
obj1 = nil // reference count = 1
obj2 = nil // reference count = 0, object is deallocated
Thus, ARC helps manage memory efficiently without the need to manually call resource release.