Junior — Middle
What steps are necessary to cause a Retain Cycle in memory?
sobes.tech AI
Answer from AI
A retain cycle in iOS occurs when two or more objects hold strong references to each other, preventing them from being deallocated, which causes a memory leak.
The steps to create a retain cycle are:
- Object A holds a strong reference to Object B.
- Object B holds a strong reference to Object A.
- Neither object is deallocated because the reference count does not reach zero.
Example:
class A {
var b: B?
}
class B {
var a: A?
}
let a = A()
let b = B()
a.b = b
b.a = a // Retain cycle
To avoid a cycle, one of the references is made weak (weak) or unowned (unowned). For example:
class B {
weak var a: A?
}
Thus, a retain cycle occurs when mutual strong references are maintained without breaking the cycle, which blocks the deallocation of objects.