Header Ads

Memory Management - Objective C

Memory management is one of the most important process in any programming language. It is the process by which the memory of objects are allocated when they are required and decallocated when they are no longer required.

Managing object memory is a matter of performance; if an application does not free unneeded objects, its memory footprint grows and performance suffers.

Objective C memory management techniques can be broadly classified into two types:
  • Manual Retain- Release or MRR
  • Automatic Reference counting or ARC

The memory life cycle of the class A object is shown in the above fig. As you can see, the retain count is shown below the object, when the retain count of an object becomes 0 , the object is feed completely and its memory is deallocated for other objects to use.

Class A object is first created using alloc/init method avaiable in NSObject. Now the retain count becomes 1.

Now, class B retains the class A's object and the retain count of class A's object becomes 2.

Then , Class C makes a copy of the object. Now, it is created as another instance of class A with same values for the instance variables. Here the retain count is 1 and not the retain count of the original object. This is represented by the dotted line in the figure.

The copied object is released by Class C using the release method and the retain count becomes 0 and hence the object is desctroyed.

In case of the inital class A object the retain count is 2 and it has to be released twice in order for it to be destroyed. This is done by release statement of class A and Class B which decrements the retain count to 1 and 0 , respectively. Finally object is destroyed.

MRR Basic Rules
  • We own any object we create : We create an object using a method whose name begins with "alloc", "new", "copy", or "mutableCopy"
  • We can take ownership of an object using retain : A received object is normally guranteed to remain valid within the method it was received in, and that method may also safely return the object to its invoker. We use retain in two situation:
  1.   In the implementation of an accessor method or an init method, to take ownership of an object we want to store as a property value.
  2. To prevent an object from being invalidated as a side effect of some other operation. 
  • When we no longer need it, we must relinquish ownership of an object we own : We relinquish ownership of an object by sending it a release  message or an autorelease message. In cocoa terminology, relinquishing ownership of an object is therefore typically referred to as "releasing an object".
  • You must not relinquish ownership of an object you do not own : This is just corollary of  the previous policy rules stated explicit;y.
#import <Foundation/Foundation.h>
@interface Sample : NSObject
  -(void)sammethod;
@end
@implementation Sample
-(void) sammethod
{
     NSLog(@"HEllo Ravi");
}
-(void)dealloc
{
     NSLog(@"object deallocated");
    [super dealloc];
}
@end
int main()
{
     Sample *obj = [[Sample alloc] init];
     [obj sammethod];
     NSLog(@"Retain count after inital allocation: %d", [obj retainCount]);
    [obj reatain];
     NSLog(@"Retain count after retain :%d", [obj retainCount]);
    [obj release];
    NSLog(@"Reatin count after release : %d", [obj retainCount]);
    [obj release];
    NSLog(@"obj dealloc will be called before this");
     obj = nil;
    return 0;
}
Automatic Reference Counting or ARC
In ARC the system uses the same reference counting system as MRR, but it inserts the appropriate memory management method calls for us at compile time. We are strongly encouraged to use ARC for new projects. If we use ARC, there is typically no need to understand the underlying implementation described although it may in some situations be helpful. For more about ARC, see Transitioning to ARC Release notes.

As mentioned above in ARC, we need not add release and retain methods since that will be taken care by the compiler. Actually the underlying process of Objective C is still the same. It uses the retain and release operations internally making it easier for the developer to code without worrying about these operations, which will reduce both the amount of code written and the possibility of memory leaks.
There was another principle called garbage collection, which is used in Mac OS - X along with MRR but since its deprecation in OS X Mountain Lion, it has not been discussed along with MRR. Also , IOS objects never had garbage collection feature. And with ARC there is no use of garbage collection in OS-X too.
Here is simple ARC example
#import <Foundation/Foundation.h>
@interface Sample : NSObject
  -(void)sammethod;
@end
@implementation Sample
-(void) sammethod
{
     NSLog(@"HEllo Ravi");
}
-(void)dealloc
{
     NSLog(@"object deallocated");
 
}
@end
int main()
{
     @autoreleasepool{
     Sample *obj = [[Sample alloc] init];
     [obj sammethod];
            obj = nil;

    }     
    return 0;
}

No comments:

Powered by Blogger.