Open In App

Classes & Objects in Objective-C

Last Updated : 14 Jun, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

Objective-C is an object-oriented programming language that has been used for developing software applications for various Apple platforms, such as iOS, macOS, watchOS, and tvOS. Classes and objects are the fundamental building blocks of object-oriented programming in Objective-C. A class is a blueprint or a template that defines the properties and behavior of objects, while an object is an instance of a class.

Objective-C provides support for various types of classes such as abstract classes, concrete classes, and root classes. It also supports various types of objects such as mutable objects, immutable objects, and singleton objects. In this article, we will discuss these concepts in detail along with syntax, keywords, and examples.

Syntax and Keywords in Objective-C for Classes and Objects

The syntax for declaring a class in Objective-C is as follows:

@interface ClassName : SuperClassName

{

  // instance variables declaration

}

// properties declaration

// methods declaration

@end

Here, ClassName is the name of the class, and SuperClassName is the name of the class from which ClassName is derived. The instance variables of the class are declared within curly braces { }. The properties and methods of the class are declared after the instance variable declaration.

The @implementation keyword is used to provide the actual implementation of the methods declared in the @interface section. The syntax for the implementation of a class is as follows:

@implementation ClassName

// methods implementation

@end

An object is an instance of a class. It is created by allocating memory for it using the alloc method and initializing it using the init method. Here’s an example of creating an object of the Car class:

Car *myCar = [[Car alloc] init];

In this example, we’ve created an object called myCar of the Car class by allocating memory for it using the alloc method and initializing it using the init method.

Once an object is created, we can access its properties and methods using dot notation. Here’s an example of accessing the make property of the myCar object:

NSString *myCarMake = myCar.make;

Here are some keywords and symbols in syntaxes:

  • @interface: Indicates the beginning of a class declaration.
  • ClassName: The name of the class is declared.
  • SuperclassName: The name of the class that the class being declared inherits from. If the class doesn’t inherit from any class, NSObject is used as the default superclass.
  • @property: Declares a property of the class. The attributes and type parts are optional and specify the attributes and type of the property.
  • type: The type of the property.
  • propertyName: The name of the property.
  • : Indicates an instance method.
  • +: Indicates a class method.
  • returnType: The return type of the method.
  • methodName: The name of the method.
  • parameterType: The type of the method parameter.
  • parameterName: The name of the method parameter.

Types of Classes

Abstract Class

An abstract class is a class that cannot be instantiated. It is used as a base class for other classes and provides a set of methods and properties that are common to all the classes that inherit from it. In Objective-C, an abstract class is defined using the @interface keyword with a method that has no implementation.

ObjectiveC




// AbstractClass.h
@interface AbstractClass : NSObject
- (void)method1;
- (void)method2;
@end
// AbstractClass.m
@implementation AbstractClass
- (void)method1 {
   NSLog(@"Method 1");
}
- (void)method2 {
   NSLog(@"Method 2");
}
@end


Concrete Class

It provides a set of methods and properties that are specific to that class. In Objective-C, a concrete class is defined using the @interface keyword with a list of instance variables, properties, and methods.

ObjectiveC




// ConcreteClass.h
@interface ConcreteClass : NSObject
@property (nonatomic, strong) NSString *property1;
@property (nonatomic, assign) int property2;
- (void)method1;
- (void)method2;
@end
// ConcreteClass.m
@implementation ConcreteClass
@synthesize property1;
@synthesize property2;
- (void)method1 {
   NSLog(@"Method 1");
}
- (void)method2 {
   NSLog(@"Method 2");
}
@end


Root Class

A root class is a class that does not inherit from any other class. In Objective-C, the root class is NSObject, which provides a set of methods and properties that are common to all the classes in Objective-C.

ObjectiveC




// MyObject.h
#import <Foundation/Foundation.h>
@interface MyObject : NSObject
@property (nonatomic, strong) NSString *name;
- (instancetype)initWithName:(NSString *)name;
@end
  
// MyObject.m
@implementation MyObject
- (instancetype)initWithName:(NSString *)name {
    self = [super init];
    if (self) {
        self.name = name;
    }
    return self;
}
@end


Types of Objects

Mutable Object

A mutable object is an object whose value can be changed after it has been created. In Objective-C, mutable objects are typically created using the NSMutable prefix, such as NSMutableString, NSMutableArray, and NSMutableDictionary.

// Creating a Mutable String

NSMutableString *mutableString = [NSMutableString stringWithString:@”Hello”];

// Appending a String

[mutableString appendString:@” World!”];

// Output: Hello World!

NSLog(@”%@”, mutableString);

Immutable Object

An immutable object is an object whose value cannot be changed after it has been created. In Objective-C, immutable objects are typically created using the NS prefix, such as NSString, NSArray, and NSDictionary.

// Creating an Immutable String

NSString *immutableString = @”Hello World!”;

// Output: Hello World!

NSLog(@”%@”, immutableString);

Singleton Object

A singleton object is an object that is instantiated only once throughout the lifetime of an application. In Objective-C, the singleton pattern is typically implemented using a static variable and a class method that returns the singleton instance.

// MySingleton.h

@interface MySingleton : NSObject

+ (instancetype)sharedInstance;

@end

// MySingleton.m

@implementation MySingleton

static MySingleton *sharedInstance = nil;

+ (instancetype)sharedInstance {

    static dispatch_once_t onceToken;

    dispatch_once(&onceToken, ^{

        sharedInstance = [[self alloc] init];

    });

    return sharedInstance;

}

@end

Example 1: A program to calculate Box Volume

ObjectiveC




#import <Foundation/Foundation.h>
  
@interface Box:NSObject {
   double len;    // Length of a box
   double br;   // Breadth of a box
   double h;    // Height of a box
}
  
@property(nonatomic, readwrite) double h;  // Property
-(double) vol;
@end
  
@implementation Box
  
@synthesize h; 
  
-(id)init {
   self = [super init];
   len = 4.0;
   br = 6.0;
   return self;
}
  
-(double) vol {
   return len*br*h;
}
  
@end
  
int main() {
   NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];    
   Box *box1 = [[Box alloc]init];    // Create box1 object of type Box
   Box *box2 = [[Box alloc]init];    // Create box2 object of type Box
  
   double vol = 0.0;             // Store the volume of a box here
   
   // box 1 specification
   box1.h = 5.0; 
  
   // box 2 specification
   box2.h = 10.0;
    
   // volume of box 1
   vol = [box1 vol];
   NSLog(@"Volume of Box1 : %f", vol);
     
   // volume of box 2
   vol = [box2 vol];
   NSLog(@"Volume of Box2 : %f", vol);
     
   [pool drain];
   return 0;
}


Output:

output

output1

This program defines a class Box in Objective-C and creates two instances of this class. The Box class has three instance variables len, br, and h, which represent the length, breadth, and height of a box, respectively. It also has a @property declaration for the h instance variable, which is a synthesized getter and setter method.

The Box class has one method called vol, which calculates and returns the volume of a box based on its length, breadth, and height.

In the main function, two instances of the Box class are created using the alloc and init methods. The h property of each box is then set to a different value, and the vol method is called on each box to calculate its volume. The volume of each box is printed using NSLog.

Finally, an NSAutoreleasePool object is created to manage memory, and the pool object is drained before the program exits.

Example 2: Creating Person Object and Implementing Method 

ObjectiveC




#import <Foundation/Foundation.h>
  
// Define a new class called Person
@interface Person : NSObject {
    NSString *name;
    int age;
}
// Declare methods for the Person class
- (void)setName:(NSString *)newName;
- (NSString *)name;
- (void)setAge:(int)newAge;
- (int)age;
@end
@implementation Person
// Implement methods for the Person class
- (void)setName:(NSString *)newName {
    name = newName;
}
- (NSString *)name {
    return name;
}
- (void)setAge:(int)newAge {
    age = newAge;
}
- (int)age {
    return age;
}
@end
  
// Main program
int main() {
    // Create a new Person object
    Person *person = [[Person alloc] init];   
    // Set the person's name and age
    [person setName:@"John"];
    [person setAge:30];
    // Print out the person's name and age
    NSLog(@"Name: %@, Age: %d", [person name], [person age]);
    // Release the person object
    [person release];
    return 0;
}


Output:

output

output2

This Objective-C program defines a class called Person that has two instance variables: name (a string) and age (an integer). The class has four methods: “setName“, “name“, “setAge“, and “age“. The setName method sets the value of the “name” instance variable, the name returns the value of the name instance variable, the setAge sets the value of the age instance variable, and “age” returns the value of the “age” instance variable.

In the main function, a Person’s object is created using the “alloc” and “init” methods. The person’s name and age are set using the setName and setAge methods, respectively. The person’s name and age are then printed using the “name” and “age” methods, respectively. Finally, the person’s object is released using the release method.



Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads