Interview PrepMidMCQ

What is retain cycle and how do you prevent it?

Test your knowledge:

Explanation & Code

Answer: A retain cycle occurs when two objects hold strong references to each other, preventing ARC from deallocating either. Memory leaks.

Common case — closure capturing self:

// ❌ Retain cycle — viewModel holds closure, closure holds viewModel
viewModel.onUpdate = {
    self.updateUI() // strong capture
}

// ✅ Break cycle with [weak self]
viewModel.onUpdate = { [weak self] in
    self?.updateUI()
}

// ✅ Or [unowned self] if self is guaranteed to outlive the closure
viewModel.onUpdate = { [unowned self] in
    self.updateUI()
}

How to find them: Xcode's Memory Graph Debugger (Debug > Memory Graph) — look for objects that still exist after they should be deallocated.

Rate your understanding:

Ready to practice more Interview Prep?

Test yourself with our interactive quiz mode or browse all curated questions for this topic.