[an error occurred while processing this directive]

Objective-c memory management: retain and release

                         


In this section we will see how to manage memory with language Objective-C. Programmer can allocate memory for the object and deallocate memory as well but we will learn what happened when object contains pointers to other objects?
Also we will see how does the Foundation framework deals with memory management when you create classes and objects.

Objective-C uses two methods retain and release. In Objective-C each object has an internal counter that is used to keep track of all references used by the objects or object has. [object retain] increments the counter by 1 and [object release] decrements the counter by 1. When counter reaches to zero, dealloc is then called.

This is simple code of memory deallocation.

-(void) dealloc {

    //show a message during deallocation.
    printf( "Deallocing fraction\n" );
    [super dealloc];
}

retainCount: retain count method is used to show the internal count of the given object so that programmer can easily increment and decrement the counter as per requirement.

Example:

MyClass.h                                                      MyClass.m       
#import<Foundation/NSObject.h>
@interface MyClass:NSObject
    // This is MyClass declaration.
@end
#import "MyClass.h"
@implementation MyClass
    // This is MyClass definition.
@end

main.m
#import "MyClass.m"
#import <stdio.h>
int main() {
   
    // create two objects my MyClass.
    MyClass *myClassObj1 = [[MyClass alloc] init];
    MyClass *myClassObj2 = [[MyClass alloc] init];
    // current internal count of the objects.
    printf("myClassObj1 retain count is : %d \n ",[myClassObj1 retainCount]);
    printf("myClassObj2 retain count is : %d \n\n",[myClassObj2 retainCount]);
    // increment their counts
    [myClassObj1 retain]; // Now count is 2
    [myClassObj2 retain]; // Now count is 2
    [myClassObj1 retain]; // Now count is 3
    // print current counts.
    printf("myClassObj1 retain count is : %d \n ",[myClassObj1 retainCount]);
    printf("myClassObj2 retain count is : %d \n\n ",[myClassObj2 retainCount]);
    // Decrement their counts.
    [myClassObj1 release]; // Now count is 2
    [myClassObj2 release]; // Now count is 1
    [myClassObj1 release]; // Now count is 1
    // print current counts.
    printf("myClassObj1 retain count is : %d \n ",[myClassObj1 retainCount]);
    printf("myClassObj2 retain count is : %d \n ",[myClassObj2 retainCount]);
 
    // now deallocate both objects.
    [myClassObj1 release];
    [myClassObj1 release];
    return 0;
}


Output
:

myClassObj1 retain count is : 1 
myClassObj2 retain count is : 1 
myClassObj1 retain count is : 3 
myClassObj2 retain count is : 2 
myClassObj1 retain count is : 1 
myClassObj2 retain count is : 1 


Download Source Code
 

                         

[an error occurred while processing this directive]