iPhone Memory Management
After long time i’m back to my web home. Passing some tough time. Well today i am going to write about iPhone memory management. Its not easy to write code without considering the memory that reserved for you. If you dont have a clear concept right now, surely you will face some problem in developing yar application. So lets have a discussion.
Memory Management
First of all Objective-C don’t have garbage collection like some other language. But i have to say the memory management is not 100% manual neither 100% automatic. Confused!!! Wait keep reading, hope you will find the answer.
Retain Count
The first technique that can help to mange your memory is retain count.
So what is retain count???
Retain Count: How many other objects have a reference of a particular object. That is how many other objects holding the reference of your declared objects. Hope you know that when you declared an object it consumed some space in your main memory and if don’t make free that space that will be a nightmare for you later. So every time you declared an object some memory occupied by your program and if you don’t dealloc it application will be crashed. So easy way to count down to find it is retain count.
In Objective C every class is derived from base class NSObject which has an property retainCount. So you can make an inquiry of your declared object with this property. Whenever you declare an object or hold the reference of an object the retainCount increased by 1 and when you release the reference, the retainCount is decreased by 1. And finally when the retainCount gets down to 0, Objective-C deletes memory for that object. So here is the summery
–[anObject retain] –> increment count by 1
–[anObject release]–> decrement count by 1
When count ==0 –>Obj C deletes memory for that object
You must release those objects which belongs to you(forget the else).
•Ownership of an object
–alloc
–new
–copy
–Retain message
You owned an object when you declare it by alloc/new, copt actually mutableCopy and by the retain message. So its yar duty to maintain retainCount. Thats the manual thing i talking about.
•Reference counting (example)
NSNumber *myInt 1= [NSNumber numberWithInteger:100] ;
//count incresed by 1
NSNumber *myInt 2;
NSMutable Array *myArray = [NSMutableArray array];
[myInt1 retainCount]; //just print to see what goin on result =1
[myArray addObject:myInt1]; //increment by 1
[myInt1 retainCount]; // result 2
myInt2 = myInt1; //holding the reference
[myInt1 retain]; //doing that b coz of earlier statement
[myArray removeObject:myInt1]; // decresed by 1
[myInt1 release]; //// decresed by 1