Objective-c Dealloc
When an object contains another objects so before deallocation programmer needs to release all those objects. This example shows how to use method dealloc, when you want to deallocate an object that has already some other objects attached.
In the example given below we have used a information system of a student, that
manage three field for the student- first name, last name and email. To declare
and store all these string values we have used super class NSString. We will
create objects of this String class and use with the object. When we want to release
the object, we need to deallocate these string objects first.
Example :
Student.h
#import <Foundation/NSObject.h> #import <Foundation/NSString.h> @interface Student: NSObject { NSString *fName; NSString *lName; NSString *email; } -(void) set: (NSString*) f last: (NSString*)l email:(NSString*)e; -(void) setFirst: (NSString*) f; -(void) setLast: (NSString*) l; -(void) setEmail: (NSString*) e; -(NSString*) firstName; -(NSString*) lastName; -(NSString*) email; -(void) print; @end |
Student.m
#import "Student.h" #import <stdio.h> @implementation Student -(void) set: (NSString*) f last: (NSString*) l email: (NSString*)e{ [self setFirst: f]; [self setLast: l]; [self setEmail: e]; } -(NSString*) firstName { return fName; } -(NSString*) lastName { return lName; } -(NSString*) email { return email; } -(void) setFirst: (NSString*) f { [f retain]; [fName release]; fName = f; } -(void) setLast: (NSString*) l { [l retain]; [lName release]; lName = l; } -(void) setEmail: (NSString*) e { [e retain]; [email release]; email = e; } -(void) print { printf( "%s %s %s", [fName cString],[lName cString], [email cString] ); } -(void) dealloc { [fName release]; [lName release]; [email release]; [super dealloc]; } @end |
myMain.m
#import "Student.m" #import <Foundation/NSString.h> #import <stdio.h> int main( int argc, const char *argv[] ) { NSString *fName =[[NSString alloc] initWithCString: "Mahendra"]; NSString *lName = [[NSString alloc] initWithCString: "Singh"]; NSString *email = [[NSString alloc] initWithCString: "[email protected]"]; Student *mahendra = [[Student alloc] init]; [mahendra set: fName last: lName email: email]; // first release string objects [fName release]; [lName release]; [email release]; // show the retain count printf( "Retain count: %i\n", [mahendra retainCount]); [mahendra print]; printf( "\n" ); // free memory [mahendra release]; return 0; } |