Objective C Category vs Extension Explained
Q: What is the difference between a category and an extension in Objective C?
- Objective C
- Mid level question
Explore all the latest Objective C interview questions and answers
ExploreMost Recent & up-to date
100% Actual interview focused
Create Objective C interview for FREE!
In Objective-C, both categories and extensions provide a way to add functionality to an existing class. However, they differ in their scope and how they can be used.
A category is a way to add new methods to an existing class, even if you don't have access to the original source code. Categories are typically used to add functionality to system classes or to organize your own code into logical groupings. You define a category in a separate file, and then import it into your code to use the added methods.
Here's an example of defining a category to add a new method to the NSString class:
// NSString+MyCategory.h @interface NSString (MyCategory) - (NSString *)reverseString; @end // NSString+MyCategory.m @implementation NSString (MyCategory) - (NSString *)reverseString { NSMutableString *reversed = [NSMutableString string]; NSInteger length = [self length]; for (NSInteger i = length - 1; i >= 0; i--) { [reversed appendString:[NSString stringWithFormat:@"%c", [self characterAtIndex:i]]]; } return reversed; } @end
You can then use this category in your code by importing the header file:
NSString *original = @"hello"; NSString *reversed = [original reverseString]; NSLog(@"%@", reversed); // Output: "olleh"
Extensions, on the other hand, are used to add methods or properties to a class's implementation. Extensions are typically used to add private methods or properties that should not be exposed to other classes. You define an extension in the same file as the class implementation, using the `@interface` directive with no name.
Here's an example of defining an extension to add a private property to a class:
// MyClass.m @interface MyClass () @property (nonatomic, strong) NSMutableArray *myPrivateArray; @end @implementation MyClass - (instancetype)init { self = [super init]; if (self) { _myPrivateArray = [NSMutableArray array]; } return self; } // Other methods... @end
In this example, we're adding a private property `myPrivateArray` to the `MyClass` implementation. This property is not visible outside of the implementation file and is only used internally.
In summary, categories are used to add new methods to an existing class, while extensions are used to add methods or properties to a class's implementation. Categories can be defined in a separate file and imported into your code, while extensions are defined in the same file as the class implementation.


