Wednesday 12 June 2013

Constructors and Creating Objects in Objective C

Hi, how are you doing guys.... I am back... I hope you guys got some familiarity with the Objective C syntax we discussed in one of my last tutorial. In this tutorial we will learn about how we write constructors/initializers and how to create an object in Objective C.

Lets start.... constructor/initializer is a method which we call while creating a new object in Object Oriented Programming. In this method we write all the code related to initial setup of an object. Objective C have a default construction called init which is present in its root class NSObject. We can override default initializer. It looks like below :

Default Initializer


- (id)init
{
    if( self = [super init] )
    {
        // Initialize your object here
    }
    
    return self;
}

Confused!!!! Lets go one by one line. 

1. - (id)init

- represents it is a class method. id is generic type. It can hold any kind of object. We will see more about id in our next tutorials. init is the initializer name.

2. ifself = [super init] )

self represents current instance/object. [super init] will call the super class initializer.

3. return self;

Finally it returns the properly initialized object.

Custom Initializer 

Okay, now lets create a custom constructor. We will take the same Employee class earlier and will try to initialize his firstName, lastName and salary. Here is the code for it :

Interface 


@interface Employee : NSObject
{
    NSString *firstName;
    NSString *lastName;
    float salary;
}

- (id)initWithFirstName:(NSString *)aFirstName
               lastName:(NSString *)aLastName
                 salary:(float)aSalary;

@end

Implementation 


#import "Employee.h"

@implementation Employee

- (id)initWithFirstName:(NSString *)aFirstName
               lastName:(NSString *)aLastName
                 salary:(float)aSalary
{
    if( self = [super init] )
    {
        firstName = aFirstName;
        lastName = aLastName;
        salary = aSalary;
    }
    
    return self;
}

@end

Above code explains how a class Employee with properties firstName, lastName and salary and a constructor looks like. Now, lets create an object of type Employee....

Object Creation

Option 1:

// Using Default Initializer
Employee *employeeWithDefaultInit = [[Employee alloc] init];
        
// Using Custom Initializer
Employee *employeeWithCustomInit = [[Employee alloc] initWithFirstName:@"Naga" lastName:@"Malleswar" salary:5000];

In the above code I have associated two method calls in single statement. We can make them two separate statements like below, but followed convention is Option 1.

Option 2:

// Using Default Initializer
Employee *employeeWithDefaultInit = [Employee alloc];
employeeWithDefaultInit = [employeeWithDefaultInit init];
        
// Using Custom Initializer
Employee *employeeWithCustomInit = [Employee alloc];
employeeWithCustomInit = [employeeWithCustomInit initWithFirstName:@"Naga" lastName:@"Malleswar" salary:5000];

Both the above options are same. Only thing is convention. Most of the programmers follow Option 1 to create objects. One may get a doubt. What is alloc is??? alloc is a method to allocate memory. Object creation completes only if we send both alloc and init messages to a new object.

Thanks for your time guys. In our next tutorial, we will create set and get methods for the properties in Employee class. Please feel free to add your comments and suggestion.

9 comments:

  1. amaizing,you are knowledged guy

    ReplyDelete
  2. thanks for the nice example ..

    ReplyDelete
  3. great example of constructor..
    thankssss

    ReplyDelete
  4. why we have to use constructor/destructor, where we have to use exactly, plz provide an example....

    ReplyDelete
  5. Helpful! One thing to prevent confusion: the "-" denotes instance method, not class method. "+" would be class method. http://stackoverflow.com/questions/1053592/what-is-the-difference-between-class-and-instance-methods
    Which makes sense, init has to refer to each instance of the class. Perhaps you meant it is a "member method", as it is associated with the class, not on its own like a function (although i suppose thats implied, a method by definition is a member function)

    ReplyDelete
  6. give me one best example , where we have to use? why we have to use?

    ReplyDelete
  7. what is the exact use of init, load, loadview , initializer, kindly expalin

    ReplyDelete
  8. nice explain about constructor in "iOS"

    ReplyDelete