Intern
What is a garbage collector?
sobes.tech AI
Answer from AI
iOS does not have a traditional garbage collector. Instead, it uses the Automatic Reference Counting (ARC) mechanism.
- Automatic mechanism: ARC automatically counts strong references to objects.
- Memory release: When the number of strong references to an object drops to zero, ARC releases the allocated memory.
- Preventing leaks: Proper use of strong, weak, and unowned references helps prevent memory leaks and strong reference cycles.
Types of references in ARC:
- Strong: Increases the reference count. Default.
- Weak: Does not increase the reference count. Automatically becomes
nilwhen the object is deallocated. Used to prevent strong reference cycles. Declared as an optional type. - Unowned: Does not increase the reference count. It is guaranteed that the object it references exists for the entire lifetime of the unowned reference. Not optional. Used when two objects have a mutual strong relationship, but one has a shorter lifetime.
Advantages of ARC:
- Predictability: Memory is released deterministically as soon as the object is no longer used.
- Performance: No overhead from background garbage collection, which can cause pauses.
- Simplicity: Developers do not need to manually manage memory in most cases, but understanding reference counting principles is necessary to prevent leaks.
Example of a strong reference cycle:
class Person {
let name: String
var apartment: Apartment? // strong reference to Apartment
init(name: String) { self.name = name }
deinit { print("\(name) is being deinitialized") }
}
class Apartment {
let unit: String
weak var tenant: Person? // weak reference to Person to prevent cycle
init(unit: String) { self.unit = unit }
deinit { print("Apartment \(unit) is being deinitialized") }
}
var john: Person?
var unit4A: Apartment?
john = Person(name: "John Appleseed")
unit4A = Apartment(unit: "4A")
john!.apartment = unit4A
unit4A!.tenant = john // Using weak here is critical
john = nil
unit4A = nil
// Without weak tenant: Both john and unit4A would not be deinitialized.
// With weak tenant: Both john and unit4A are deinitialized correctly.