Objective C stack and heap

https://mikeash.com/pyblog/friday-qa-2010-01-15-stack-and-heap-objects-in-objective-c.html

Stack
  • The stack is a region of memory which contains storage for local variables, as well as internal temporary values and housekeeping.
  • On a modern system, there is one stack per thread of execution.
  • When a function is called, a stack frame is pushed onto the stack, and function-local data is stored there.
  • When the function returns, its stack frame is destroyed.
Heap

The heap is, essentially, everything else in memory.

  • Memory can be allocated on the heap at any time, and destroyed at any time.
  • You have to explicitly request for memory to be allocated from the heap, and if you aren’t using garbage collection, explicitly free it as well.
  • This is where you store things that need to outlive the current function call. The heap is what you access when you call malloc and free.

Stack vs Heap Objects

Given that, what’s a stack object, and what’s a heap object?

First, we must understand what an object is in general. In Objective-C (and many other languages), an object is simply a contiguous blob of memory with a particular layout.

The precise location of that memory is less important. As long as you have some memory somewhere with the right contents, it’s a working Objective-C object. In Objective-C, objects are usually created on the heap:

NSObject *obj = [[NSObject alloc] init];

The storage for the obj pointer variable itself is on the stack
but the object it points to is in the heap.
In other words, the obj pointer variable is pushed onto the stack. The NSObject object that it points to, is allocated on the heap

The [NSObject alloc] call allocates a chunk of heap memory, and fills it out to match the layout needed for an NSObject.

Using NS Collection classes with blocks

Since Blocks are objective C objects that gets pushed onto the stack…

A Block is the one instance of an Objective-C object that starts on the stack. While you can happily collect together a bunch of Blocks in one of the Foundation provided collection classes (NSArray, NSDictionary, or NSSet), make sure you copy the Block before you do!

The last thing you want is a stack based object to end up in an autorelease pool….

The reason why Blocks start on the stack is because it is really really fast. Orders of magnitude faster than allocating a chunk of memory for each Block.

other ref-

http://stackoverflow.com/questions/79923/what-and-where-are-the-stack-and-heap