Junior — Middle
When can you say that an object or structure is not placed on the stack?
sobes.tech AI
Answer from AI
An object or structure is not placed on the memory stack if it is allocated dynamically or has a lifespan longer than the execution time of a function.
In iOS (and generally in Swift/Objective-C):
- Local variables and structures are usually placed on the stack.
- Class objects (reference types) are allocated on the heap, and only a reference to them is stored on the stack.
- If an object is created via
alloc/initin Objective-C or viaclassin Swift, it is placed on the heap.
Example in Swift:
func example() {
let localStruct = MyStruct() // on the stack
let object = MyClass() // object on the heap, reference on the stack
}
Thus, if a variable is a reference to a class object, the object itself is outside the stack, on the heap.