Monday, October 18, 2010

Memory Mangament in iPhone


Memory management with Iphone becomes mandatory , as the iphone OS donot handle garbage collection. Apple has not included the feature of memory management , with concern that , the burden on the IPhone OS will be more. The disadvatage of this is the application crashes from the user prespective . But the advantage with this is with the programmers to some extent, because the user will have the flexibility of playing around    with memory.

Here are some of the possibilities that would lead to crash if memory is not mangaed properly.

1) First and foremost that an iphone programmer needs to know is how the retain count for the objects work.
Once you allocate an object then the retain count will be 1. If you retain the same for further computation then the retain count increases by 1 again . So totoally the retain count becomes 2.
Therefore before the scope ends , the object should be released twice.Here is the sample code snippet that explains the same.
NSString *string1=[[NSString alloc] init]; // retain count = 1
NSString *string1Copy = [string1 retain] ; // retain count = 2

2) Try using Instruments to check for any memory leaks . Visit the following the following site given by apple.

3) If the code block uses too much memory and if your not sure about the release useNSAutoReleasePool . Make sure u release this pool before the scope ends.

4) Try not using autorelease as much as possible

5) Handling of delegates : This is very important since , in the code if u assign an object to a delegate and u deallocate the object without clearing the reference , error is thrown as deallocated object is referenced , since the delegate references the object that is already released

No comments:

Post a Comment