Question

Stack-based object will not be copied to the heap if you send it a retain message; it will only be copied upon receipt of the copy message.Please explain.

Was it helpful?

Solution

Most objects are allocated on the heap, and their lifetime is determined by how many retains and releases they get. But blocks are a special kind of object that is normally allocated on the stack. This means that when the stack frame is popped (e.g. when your function returns), the memory for the block will be open to overwriting. Sending a stack-based block retain will not turn it into a heap-based object, so it will still be open to overwriting even if you retain it. The only way to keep the block around past the function's end is to copy it, which puts the copy on the heap.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top