What is Constructors and Creating Objects in Objective C !

What is Constructors and Creating Objects in Objective C !

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



1. – (id)init

– represents it is a class method. id is generic type. It can hold any kind of object. init is the initializer name.

2. if( self = [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

Create a custom constructor. We will take the Employee class and will try to initialize his firstName, lastName and salary. :

Interface (.h)




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:

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:

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.