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
- (id)init
{
if( self = [super init] )
{
// Initialize your object here
}
return self;
}
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)
@interface Employee : NSObject
{
NSString *firstName;
NSString *lastName;
float salary;
}
- (id)initWithFirstName:(NSString *)aFirstName
lastName:(NSString *)aLastName
salary:(float)aSalary;
@end
Implementation(.m)
#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:@"Mycode" lastName:@"Tips" salary:12000];
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:@"Mycode" lastName:@"Tips" salary:12000];
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.
Discover more from mycodetips
Subscribe to get the latest posts sent to your email.