|
| 1 | +--- |
| 2 | +title: "iOS Memory" |
| 3 | + |
| 4 | +categories: |
| 5 | + - iOS |
| 6 | + - Memory |
| 7 | +tags: |
| 8 | + - Memory |
| 9 | +--- |
| 10 | + |
| 11 | +## App Memory's Four Segments |
| 12 | + |
| 13 | + |
| 14 | + |
| 15 | +1. **Code**: Machine code compiled from source code |
| 16 | +1. **Data**: Global variables, static variables, static literals |
| 17 | +1. **Heap**: Dynamically allocated data (size and lifetime determined at runtime) |
| 18 | + 1. Reference types |
| 19 | + 1. Class objects |
| 20 | + 1. Internal buffers of arrays, strings, and dictionaries |
| 21 | + 1. But they behave like value types via copy-on-write |
| 22 | + 1. Escaping closures' captured contexts & mutable capture boxes |
| 23 | + 1. May include value types when needed |
| 24 | + 1. Because the closure must be able to access them later when it executes |
| 25 | + 1. Lifetime Managed by ARC |
| 26 | +1. **Stack segment**: Function call frames |
| 27 | + 1. Return addresses, saved registers, storage slots for parameters and local variables, temporaries |
| 28 | + 1. Lifetime managed automatically in LIFO order when the scope ends |
| 29 | + 1. One per thread |
| 30 | + 1. Limited capacity, so deep recursion can cause a stack overflow |
| 31 | + |
| 32 | +## Closure's captured contexts & mutable capture boxes |
| 33 | +1. A closure’s code resides in the code (text) segment.<br> A closure value consists of a code pointer and a context pointer.<br> That value is stored wherever the variable or property that holds the closure is stored. |
| 34 | +1. Escaping Closure: the closure can be stored and executed later |
| 35 | +1. Captured Contexts & mutable capture boxes |
| 36 | + |
| 37 | + |
| 38 | + |
| 39 | +~~~ |
| 40 | +let f = { print("hi") } // no capture -> no context |
| 41 | +
|
| 42 | +let x = 10 |
| 43 | +let g = { print(x) } // context: [x=10], no boxes |
| 44 | +
|
| 45 | +var n = 0 |
| 46 | +let c2 = { print(n) } // context: [&box], box(n) |
| 47 | +
|
| 48 | +var n = 0 |
| 49 | +let c3 = { n += 1 } // context: [&box], box(n) |
| 50 | +~~~ |
| 51 | +{: .language-swift} |
| 52 | + |
| 53 | +## Reference Types & Value Types |
| 54 | + |
| 55 | +1. Reference Types |
| 56 | + 1. `Class` |
| 57 | + 1. `Actor` |
| 58 | + 1. Closure |
| 59 | + 1. `NSObject` |
| 60 | + 1. UIKit/AppKit types (e.g., `UIView`, `UIColor`) |
| 61 | +1. Value Types |
| 62 | + 1. Primitive types: `Int`, `Float`, `Double`, `Bool`, `Character` |
| 63 | + 1. `String` |
| 64 | + 1. Collection types: `Array`, `Set`, `Dictionary` |
| 65 | + 1. `Tuple` |
| 66 | + 1. `Struct` |
| 67 | + 1. `Enum` |
| 68 | + 1. `Optional` |
| 69 | + |
0 commit comments