Classes Objects And Methods in Objective-C

Filed Under: iOS

In this tutorial we’ll give a brief overview of Classes and Objects and their use in Objective-C programming.

Overview

In Object-Oriented Programming a Class represents the blue-prints of an object and its no different here. Generally, in objective-C code a class is represented in two files. A header file and an implementation file.

The header file is the interface for the class and it defines the properties and methods used in the class. The implementation file contains the code that brings these properties and methods into action.

The header file is used by other classes to interact with the current class. The implementation file is private to each class. The header file is defined under @interface and the implementation class is defined under @implementation.

Creating Classes in Objective-C using XCode

Let’s create a new Custom class in a new XCode Project. Following are the steps to create the same.
objective-c-choost-template-image

objective-c-new-project-image

We’ve create a sample project to calculate Body Max Index(BMI) and display it in the command line.
We now have a file called main.m in the BMI folder in the navigation sidebar. To add the header file right click the BMI folder -> New file .. . A dialog pops up to choose the type of file. Select Header file in this case. After that enter the filename and select the properties as shown in the images below:

objective-c-new-file-image

objective-c-file-properties-image

You can see a main.h file in the navigation sidebar. All files with.h file extension are headers file and they contain the interface of the class. The .m extension files are the implementation file.

Interface file

Currently the interface file is empty. After importing the Foundation Framework and adding the interface directive @interface it should look like the image below

objective-c-header-empty-image

In Objective-C every new class is declared with an @interface, followed by the custom class name, followed by a colon and ending with the name of the superclass. In this example we’ve used NSObject as our superclass. All classes are derived from NSObject since its the base class. It is the superclass of all Objective-C classes.

Everything between the @interface line and the @end line describes what is contained in the class.

Properties are used to provide access to class instance variables in other classes.
Declaring a property always starts with @property followed by property attributes. Following are some important attributes :

  • assign : It’s used to assign a new value to the property anytime
  • nonatomic : Thread access is faster. But we cannot simultaneously access and change the value
  • readonly : We cannot directly assign new values to these properties
  • copy : The value assigned to the property can be copied and used for other purposes
  • readwrite : We can read and change the value of a property
  • strong : We have direct control over the lifetime of the property
  • weak : We can nullify the property and so can the compiler

The instance variables of the class object are defined in curly braces. Instance variables store the individual characteristics of each object. Instance Methods are defined just above @end and the following syntax is used.


- (void)enterInfo;

(void) indicates that these methods don’t return anything to the caller.
@end indicates that we’re done defining the class. In this example let’s define a sample interface for a BMI calculator.

main.h


#import <Foundation/Foundation.h>

@interface BMI : NSObject

{
    int weight;
}

@property(nonatomic, readwrite) double height;

-(double) bmi;


@end

The instance variables are private and are only accessible inside the class implementation. Method declarations begin with either a minus (-) or a plus sign (+). The minus sign indicates that this method is an instance method. This means that an object of the class must be created and initialised to call this method.
Class methods (beginning with the plus sign), can be used simply by referencing the class. No instance of the class is needed.

Implementation File

The implementation of the class is found in the file main.m in the navigation sidebar. We need to add the following preprocessor statement in this class to complete our BMI class.

#import "main.h"

Every time we create a class we need to import the interface file into the implementation file like the above statement. Just like declaring an interface we need to declare an implementation by using the @implementation directive followed by the class name that is BMI in this case.

Primarily, we see method definitions inside the implementation. The method signature needs to be exactly the same like in the header file. Class objects are initialised and allocated in the following way :

BMI *person = [[BMI alloc]init];

Instantiation is a two-step process:

  • We must allocate some memory for the object by calling the alloc method
  • We need to initialise it so it’s ready to use. We should never use an uninitialised object

init is the default initialisation method of Objective-C. We can define our own versions to assign the variables and parameters. init are just simple instance methods.

To call a method on an Objective-C object, we need to place the instance and the method in square brackets, separated by a space. Arguments(if any) are passed after the method name, preceded by a colon. Below is a sample call snippet.

[person bmi];

@synthesize directive creates a getter and a setter for the variable. Below is the snippet using this directive.

@synthesize height;

Note : We’ve not specified the instance variable name in the above snippet. Hence the name is same as the property name. If we wish to assign a different name, the following syntax is used

@synthesize propertyName = instanceVariableName;

The implementation file main.m is given below :
main.m


#import <Foundation/Foundation.h>
#import "main.h"

@implementation BMI

@synthesize height;

-(id)init
{
    self = [super init];
    weight = 68;
    return self;
}

-(double) bmi
{
    return weight/(height*height);
}
@end


int main(int argc, const char * argv[]) {
    @autoreleasepool {
        
        BMI *person = [[BMI alloc]init];
        
        double result = 0.0;     // Store the bmi result here
        
        
        person.height = 1.7272;
        
        result = [person bmi];
        NSLog(@"BMI of Person is : %f", result);
        
        
    }
    return 0;
}

The following output is produced by running the above command line program.
objective-c-classes-objects-outptut

This tutorial was aimed at giving a brief overview of the objective-c. We’ll discuss in-depth in the iOS Tutorial Series.

Leave a Reply

Your email address will not be published. Required fields are marked *

close
Generic selectors
Exact matches only
Search in title
Search in content
Search in posts
Search in pages