Junior — Middle
Can the presence of a strong reference in one entity lead to memory leaks?
sobes.tech AI
Answer from AI
Yes, the presence of strong references between objects in iOS can lead to memory leaks, especially if a cyclic reference (retain cycle) occurs. This happens when two objects hold strong references to each other, and the ARC system cannot release them because their reference counts do not reach zero.
To prevent such leaks, weak (weak) or unowned (unowned) references are used, which do not increase the reference count and allow breaking the cycle.
Example of a cyclic reference:
class Person {
var apartment: Apartment?
}
class Apartment {
var tenant: Person?
}
let person = Person()
let apartment = Apartment()
person.apartment = apartment
apartment.tenant = person // here a retain cycle occurs
To avoid the leak, one of the references can be made weak:
class Apartment {
weak var tenant: Person?
}