iOS Basic Memory ManagementAugust 09, 2011 08:06 am Posted By: bytedissident
When developing with iOS it is the developers responsibility to manage the memory usage of their application. This is often a tricky spot that can cause confusion, but is ultimately not too hard to get under your belt.
The two things that happen when memory is mis-managed is:
- Memory Leaks
- This causes your memory foot print to grow and slows down your app and can potentially lead t your app crashing to being shut down by OS
- Over releasing
- This happen when we attempt to free an object from memory that is not currently held in memory. This results in a crash.
Memory management follows a pretty simple rule, if you created it you have to release it from memory.
What do you mean by create? We create with the following methods:
Each of the above results in allocating RAM for an object.
How does the OS deal with memory management?
The OS keeps track of the retain count of each object and when the retain count of an object gets to Zero the dealloc method is called by the OS and the object is released from Memory.
What is a retain count?
retain count literally means the number of times an object is retained by memory. For instance:
UIView *tempView = [UIView alloc]init];
The above object would have a retain count of 1. If we then allocated the same object again with copy, retain or new it would grow by 1 each time. For each increment of the retain count we need to release it with the release method
[tempView release];
tempView = nil -> we add nil here so that we prevent future crashes. If a method is called on a nil object it will not crash.
Every time you call the release method the retain count goes down by 1, until it gets to Zero at which point the OS calls dealloc and it is released from memory. You should never call dealloc the OS will do this for you.
The Autorelease pool.
The Autorelease Pool is a list of objects that the gets released from memory at the end of a code block. An event loop is created Automatically by UIKit for every event iteration, like a tap or swipe. So for example if you allocate an instance of an object and send it the autorelease message then as soon as the user interacts the autorelease pool is drained when it completes and it releases your object from memory. Therefore, it’s important not to use autorelease on objects that are required for a longer length of time.
For further study on Autorelease pools I would recommend checking out Apple’s Docs
http://developer.apple.com/library/iOS/#documentation/Cocoa/Conceptual/MemoryMgmt/Articles/mmAutoreleasePools.html#//apple_ref/doc/uid/20000047-CJBFBEDI
|