Junior — Middle
What causes memory leaks in applications?
sobes.tech AI
Answer from AI
Memory leaks in applications occur when memory allocated for objects or data is not released after they are no longer needed. In iOS, this is often related to:
- Cyclic references between objects (retain cycles), especially when using ARC (Automatic Reference Counting). For example, when two objects reference each other strongly, they are not released.
- Incorrect use of closures that capture self strongly.
- Not releasing resources such as timers, observers, or file descriptors.
Example of a retain cycle with a closure:
class ViewController {
var closure: (() -> Void)?
func setup() {
closure = {
print(self) // self is captured strongly, creating a cycle
}
}
}
To avoid leaks, weak or unowned references are used in closures, and proper management of object lifecycle is maintained.