Wednesday, 12 November 2014

Memory Management in Objective C

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. All of this happens automatically, without the programmer taking any explicit action other than calling a function.

Heap
The heap is, essentially, everything else in memory. (Yes, there are things other than the stack and heap, but let's ignore that for this discussion.) 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

Copy
The copy in objective C is used to save a state of an object . It's generally used when an object have multiple owners and you are willing to save its current value. (Used for Mutable Objects)

Assign
The assign will generate a setter with assigns the value to the instance variable  directly, rather then copying or retaining it. This is best for primitive type like NSInteger and CGFloats or objects you don't own like delegates . 

The assign basically creates a weak pointer to the object and you need to make it nil or else it may become dangling pointer. 

No comments:

Post a Comment