How do the terms weak, strong, and unowned differ in the context of memory management?
sobes.tech AI
Answer from AI
In the context of memory management in Swift (iOS), the terms weak, strong, and unowned refer to types of references that affect reference counting (ARC) and help avoid retain cycles.
-
strong — this is a regular strong reference that increases the reference count of an object. As long as there is at least one strong reference, the object will not be deallocated.
-
weak — a weak reference that does not increase the reference count. It is used to avoid retain cycles. A weak reference automatically becomes
nilwhen the object it refers to is deallocated. Therefore, weak properties must be optional. -
unowned — also does not increase the reference count, but unlike
weak, it is not optional and does not becomenil. It is assumed that the object referenced byunownedwill exist longer than the reference. If the object is deallocated and anunownedreference is used, a runtime error will occur.
Example:
class Person {
var name: String
init(name: String) { self.name = name }
var apartment: Apartment?
}
class Apartment {
let unit: String
unowned let tenant: Person
init(unit: String, tenant: Person) {
self.unit = unit
self.tenant = tenant
}
}
let john = Person(name: "John")
let apt = Apartment(unit: "4A", tenant: john)
john.apartment = apt
Here, tenant is unowned because Apartment should not hold a strong reference to Person, but Person is guaranteed to exist longer than Apartment.
If there was a situation where the object could disappear earlier, it is better to use weak.