Upgrade to Pro — share decks privately, control downloads, hide ads and more …

Memory Management on iOS

Memory Management on iOS

Questions about memory management are some of the most frequently missed questions in an iOS interview. In this talk, I'll reinforce your knowledge on this critical subject, so you'll feel more comfortable asking or answering questions on this subject in your next interview.

Robin Kanatzar

May 01, 2023
Tweet

More Decks by Robin Kanatzar

Other Decks in Technology

Transcript

  1. How does iOS handle memory management? ARC Automatic Reference Counting

    Retain Cycle Two objects hold strong references to each other Strong or weak References
  2. Reference Counting MyClass Reference count = 1 MyClass Reference count

    = 2 Strong reference Weak reference Strong reference MyClass Reference count = 0
  3. ARC Can handle retain cycles Can NOT handle retain cycles

    NOT immediately deallocated Garbage Collection vs Immediately deallocated
  4. class Teacher { var student: Student? } class Student: UIViewController

    { let teacher = Teacher() func viewDidLoad() { teacher.student = self } } Retain Cycle Two objects hold strong references to each other Teacher ⇔ Student
  5. class Teacher { weak var student: Student? } class Student:

    UIViewController { let teacher = Teacher() func viewDidLoad() { teacher.student = self } }
  6. class Teacher { let firstName = "Mary" let lastName =

    "Jones" lazy var name: () -> String = { self.lastName + "," + self.firstName } } Retain Cycle Two objects hold strong references to each other Class ⇔ Closure
  7. class Teacher { let firstName = "Mary" let lastName =

    "Jones" lazy var name: () -> String = { [weak self] in self?.lastName + "," + self?.firstName } }
  8. let operation: Observable<String> = service.fetchName() operation .subscribe(onNext: { name in

    let workItem = DispatchWorkItem { [weak self] in self?.nameLabel.text = name } self.workItem = workItem }) .disposed(by: disposeBag)
  9. let operation: Observable<String> = service.fetchName() operation .subscribe(onNext: { [weak self]

    name in let workItem = DispatchWorkItem { in self?.nameLabel.text = name } self?.workItem = workItem }) .disposed(by: disposeBag)
  10. class Teacher { let firstName = "Mary" func getName(completion: (String?)

    -> ()) { completion(self.firstName) } } Non-escaping closure Immediate In-scope Not stored for later
  11. class Teacher { let firstName = "Mary" func getName(completion: @escaping

    (String?) -> ()) { [weak self] in completion(self?.firstName) } } Escaping closure Can leave scope Can be stored for later Can be run in future