iOS Memory
iOS Memory
App Memory’s Four Segments
- Code: Machine code compiled from source code
- Data: Global variables, static variables, static literals
- Heap: Dynamically allocated data (size and lifetime determined at runtime)
- Reference types
- Class objects
- Internal buffers of arrays, strings, and dictionaries
- But they behave like value types via copy-on-write
- Escaping closures’ captured contexts & mutable capture boxes
- May include value types when needed
- Because the closure must be able to access them later when it executes
- Lifetime Managed by ARC
- Reference types
- Stack segment: Function call frames
- Return addresses, saved registers, storage slots for parameters and local variables, temporaries
- Lifetime managed automatically in LIFO order when the scope ends
- One per thread
- Limited capacity, so deep recursion can cause a stack overflow
Closure’s captured contexts & mutable capture boxes
- 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. - Escaping Closure: the closure can be stored and executed later
- Captured Contexts & mutable capture boxes
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
- Reference Types
ClassActor- Closure
NSObject- UIKit/AppKit types (e.g.,
UIView,UIColor)
- Value Types
- Primitive types:
Int,Float,Double,Bool,Character String- Collection types:
Array,Set,Dictionary TupleStructEnumOptional
- Primitive types:
This post is licensed under CC BY 4.0 by the author.

