Sunday, April 24, 2011

Memory Management

An important concept in programming is memory handling. If you come from C you might know of pointers, they point to a certain memory location. So if you declare
int *num
The num variable will point to a certain location in memory. To reserve this memory for future use in C malloc or calloc is used, and after this space is reserved it is totally our responsibility to handle it, the system won't use this space at all during the execution of the program. So let us reserve 10 bytes of memory by using malloc and letting num point to that block of memory. Now in case you have done all of this in a function, the memory is reserved though out runtime but the num pointer won't be accessible outside the function. So oustide the function even though the memory is reserved you won't be able to access that memory and make changes to it.


Memory management in iOS is also very similar to this, almost all variables in iOS are pointers and memory is allocated to it through the alloc function. For ex if you want to allocate memory to an NSString pointer variable, you would do something like
NSString *string = [[NSString alloc] init];


So now the string has been allocated memory and you may use it in your code. Now since you are the one who allocated memory to the string you should be the one to deallocate memory from it. Now the SDK offers a dealloc method which you can call explicitly to free up the allocated memory but this isn't considered good practice, instead the SDK provides a convenient way to tell the OS that you have done your bit towards memory handling and now it is totally the system's responsibility to take care of the memory and ensure that it doesn't leak. This practice comes in handy when the object is needed by the system but you don't need a reference to it anymore, for ex after adding a viewcontroller to the navigation controller, a reference to the view controller isn't generally required. So you would tell the OS that I am releasing the object from my side and now it is your responsibility to take care of it. This code fragment will better explain the view controller and navigation controller example
UIViewController *vc = [[UIViewController alloc] init];
UINanigationController *navController = [[UINavigationController alloc] initWithRootViewController:vc];
[vc release];


So in the first line we allocate memory to the view controller, in the second line we allocate memory to a navigation controller and assign the previously declared view controller as the navigation controllers root view controller. After doing this we no longer need a reference to vc so we call the release method on vc and tell the os to take care of the memory,


So whenever you call alloc be sure to call release otherwise you will create a memory leak and increase the memory footprint of your app, you sure don't want that to happen.

No comments: