Open In App

Interface in Objective-C

Last Updated : 17 May, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

Objective-C is an object-oriented programming language that was developed by Apple Inc. for its operating systems. One of the fundamental concepts of object-oriented programming is the ability to define interfaces, which specify the methods and properties that an object must have in order to be considered a member of a particular class or category. In Objective-C, interfaces play a crucial role in defining the structure and behavior of classes and objects.

In this article, we will discuss the concept of interfaces in Objective-C in detail, including the different types of interfaces that are available, their syntax and related keywords, and examples of how to use them in your code.

What is an Interface in Objective-C?

An interface in Objective-C is a blueprint or contract that specifies the methods and properties that an object must have in order to be considered a member of a particular class or category. Interfaces define the public API of a class, which is the set of methods and properties that can be accessed by other objects in the program. Interfaces provide a way to enforce encapsulation and modularity in your code. By defining a clear boundary between the public and private parts of your code, you can make it easier to maintain and update your codebase over time.

Types of Interfaces in Objective-C

There are four main types of interfaces in Objective-C:

Class Interface

A class interface defines the public API of a class. It declares the methods and properties that are accessible from outside the class. Class interfaces are declared in header files and are typically used to define the behavior of custom classes.

Example:

@interface MyClass : NSObject

{

// Instance variables

}

// Properties

@property (nonatomic, strong) NSString *name;

// Methods

(void)doSomething;

@end

Protocol Interface

A protocol interface defines a set of methods that an object must implement in order to be considered a member of a particular protocol. Protocols are declared using the @protocol keyword and can be adopted by any class that implements the required methods.

Example:

@protocol MyProtocol

(void)doSomething;

@end

@interface MyClass : NSObject <MyProtocol>

{

// Instance variables

}

// Properties

@property (nonatomic, strong) NSString *name;

@end

Category Interface

A category interface allows you to add methods and properties to an existing class without subclassing it. Category interfaces are declared using the @interface keyword with the name of the class being extended in parentheses, followed by the category name.

Example:

@interface NSString (MyCategory)

(NSString *)reversedString;

@end

Formal Protocol Interface

A formal protocol interface is a protocol that is defined using a combination of the @protocol and @interface keywords. Formal protocols allow you to declare optional and required methods, as well as properties and can be adopted by any class that conforms to the protocol.

Example:

@protocol MyFormalProtocol <NSObject>

@required

(void)requiredMethod;

@optional

(void)optionalMethod;

@property (nonatomic, strong) NSString *optionalProperty;

@end

Syntax and Related Keywords

Here are some of the keywords and syntax that are commonly used when working with interfaces in Objective-C:

  1. @interface: This keyword is used to declare an interface.
  2. @protocol: This keyword is used to declare a protocol.
  3. @property: This keyword is used to declare a property.
  4. : NSObject: This specifies the class that the interface inherits from.
  5. <MyProtocol>: This specifies the protocol that the interface adopts.
  6. (MyCategory): This specifies the category that the interface extends.
  7. @required: This keyword is used to specify required methods in a formal protocol.
  8. @optional: This keyword is used to specify optional methods in a formal protocol.

Example Code 1: Using Class Interface

In this example, we will create a custom class named “Person” with a class interface that defines a property for the person’s name and a method for printing a greeting.

ObjectiveC




// Person.h
  
@interface Person : NSObject
  
@property (nonatomic, strong) NSString *name;
  
- (void)sayHello;
  
@end
  
  
// Person.m
  
@implementation Person
  
- (void)sayHello {
    NSLog(@"Hello, my name is %@", self.name);
}
  
@end
  
  
// main.m
  
#import "Person.h"
  
int main(int argc, const char * argv[]) {
    @autoreleasepool {
        Person *person = [[Person alloc] init];
        person.name = @"John";
        [person sayHello];
    }
    return 0;
}


Output:

output

 

In this code, we declare a class interface for the Person class in the header file “Person. h”. We declare a property for the person’s name and a method for printing a greeting. In the implementation file “Person.m”, we define the method for printing the greeting using NSLog. In the main function, we create a Person object, set the name property to “John”, and call the sayHello method to print the greeting.

Example Code 2: Using Protocol Interface

In this example, we will define a protocol named “Shape” with two required methods for calculating the area and perimeter of a shape. We will then create a custom class named “Rectangle” that adopts the Shape protocol and implements the required methods.

ObjectiveC




// Shape.h
  
@protocol Shape <NSObject>
  
@required
- (float)calculateArea;
- (float)calculatePerimeter;
  
@end
  
  
// Rectangle.h
  
#import "Shape.h"
  
@interface Rectangle : NSObject <Shape>
  
@property (nonatomic, assign) float width;
@property (nonatomic, assign) float height;
  
@end
  
  
// Rectangle.m
  
@implementation Rectangle
  
- (float)calculateArea {
    return self.width * self.height;
}
  
- (float)calculatePerimeter {
    return 2 * (self.width + self.height);
}
  
@end
  
  
// main.m
  
#import "Rectangle.h"
  
int main(int argc, const char * argv[]) {
    @autoreleasepool {
        Rectangle *rectangle = [[Rectangle alloc] init];
        rectangle.width = 10;
        rectangle.height = 5;
        NSLog(@"Area: %.2f", [rectangle calculateArea]);
        NSLog(@"Perimeter: %.2f", [rectangle calculatePerimeter]);
    }
    return 0;
}


Output:

output

 

In this code, we declare a protocol interface for the Shape protocol in the header file “Shape.h”. We define two required methods for calculating the area and perimeter of a shape. In the header file “Rectangle.h”, we declare a custom class named “Rectangle” that adopts the Shape protocol. We also declare properties for the width and height of the rectangle. In the implementation file “

Example Code 3: Using Category Interface:

In this example, we will use a category interface to add a new method to the NSString class.

ObjectiveC




// NSString+Reverse.h
  
@interface NSString (Reverse)
  
- (NSString *)reverseString;
  
@end
  
  
// NSString+Reverse.m
  
@implementation NSString (Reverse)
  
- (NSString *)reverseString {
    NSMutableString *reversedString = [NSMutableString stringWithCapacity:[self length]];
    [self enumerateSubstringsInRange:NSMakeRange(0,[self length])
                             options:(NSStringEnumerationReverse | NSStringEnumerationByComposedCharacterSequences)
                          usingBlock:^(NSString *substring, NSRange substringRange, NSRange enclosingRange, BOOL *stop) {
        [reversedString appendString:substring];
    }];
    return reversedString;
}
  
@end
  
  
// main.m
  
#import "NSString+Reverse.h"
  
int main(int argc, const char * argv[]) {
    @autoreleasepool {
        NSString *originalString = @"hello world";
        NSString *reversedString = [originalString reverseString];
        NSLog(@"Original string: %@", originalString);
        NSLog(@"Reversed string: %@", reversedString);
    }
    return 0;
}


Output:

output

 

In this code, we define a category interface for the NSString class in the header file “NSString+Reverse.h”. We declare a new method called “reverseString” that returns the reverse of the input string. In the implementation file “NSString+Reverse.m”, we implement the method using the enumerateSubstringsInRange method to reverse the string. In the main function, we create a string object, call the reverseString method to reverse the string, and print both the original and reversed strings.

Conclusion

Interfaces in Objective-C provide a way to define the public interface of a class or protocol. They allow us to declare properties and methods that can be accessed by other classes or objects. There are several types of interfaces in Objective-C, including class interfaces, protocol interfaces, and category interfaces. Each type has its own syntax and keywords that are used to declare properties, methods, and protocols. By understanding the basics of interfaces, developers can create more modular and extensible Objective-C code.



Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads