Post

iOS Memory

iOS Memory

App Memory’s Four Segments

image

  1. Code: Machine code compiled from source code
  2. Data: Global variables, static variables, static literals
  3. Heap: Dynamically allocated data (size and lifetime determined at runtime)
    1. Reference types
      1. Class objects
    2. Internal buffers of arrays, strings, and dictionaries
      1. But they behave like value types via copy-on-write
    3. Escaping closures’ captured contexts & mutable capture boxes
      1. May include value types when needed
      2. Because the closure must be able to access them later when it executes
    4. Lifetime Managed by ARC
  4. Stack segment: Function call frames
    1. Return addresses, saved registers, storage slots for parameters and local variables, temporaries
    2. Lifetime managed automatically in LIFO order when the scope ends
    3. One per thread
    4. Limited capacity, so deep recursion can cause a stack overflow

Closure’s captured contexts & mutable capture boxes

  1. A closure’s code resides in the code (text) segment.
    A closure value consists of a code pointer and a context pointer.
    That value is stored wherever the variable or property that holds the closure is stored.
  2. Escaping Closure: the closure can be stored and executed later
  3. Captured Contexts & mutable capture boxes

image

1
2
3
4
5
6
7
8
9
10
let f = { print("hi") } // no capture -> no context

let x = 10
let g = { print(x) } // context: [x=10], no boxes 

var n = 0
let c2 = { print(n) } // context: [&box], box(n)

var n = 0
let c3 = { n += 1 } // context: [&box], box(n)

Reference Types & Value Types

  1. Reference Types
    1. Class
    2. Actor
    3. Closure
    4. NSObject
    5. UIKit/AppKit types (e.g., UIView, UIColor)
  2. Value Types
    1. Primitive types: Int, Float, Double, Bool, Character
    2. String
    3. Collection types: Array, Set, Dictionary
    4. Tuple
    5. Struct
    6. Enum
      1. Optional
This post is licensed under CC BY 4.0 by the author.