01. The ways to extend a class in Objective-C

It will take about 1 minutes to finish reading this article.

1. Category

Categories allow you to add methods to a class without modifying the original class interface. You can place the implementation of a class in a separate file and use the extended methods by importing that file.

Example:

1
2
3
4
5
6
7
8
9
10
11
12
// MyClass+Extension.h
@interface MyClass (Extension)
- (void)newMethod;
@end

// MyClass+Extension.m
@implementation MyClass (Extension)
- (void)newMethod {
// new logic code
}
@end

2. Extension

An extension is a special form of class that allows you to declare private properties and methods in the same file. Extensions are merged with the original class’s definition at compile time and require no additional imports.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
//MyClass.h
@interface MyClass : NSObject
//Public interface
@end

//MyClass.m
@interfaceMyClass()
// Private interface in extension
@property (nonatomic, strong) NSString *privateProperty;
- (void)privateMethod;
@end

@implementationMyClass
// Class implementation
@end

3. Inheritance

You can create a new class that inherits from the original class and add or modify methods in the new class. This way, the new class will inherit all properties and methods of the original class, and you can add your own logic in the new class.

1
2
3
4
5
6
7
8
9
10
11
12
13
// MySubclass.h
@interface MySubclass : MyClass
// new method
- (void)newMethod;
@end

// MySubclass.m
@implementation MySubclass
- (void)newMethod {
// implement new method
}
@end

4. Protocol

You can add a set of method declarations to a class by implementing a protocol. Similar to interfaces in Java or other object-oriented languages, a protocol defines a set of methods, and classes implement these methods.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
//MyProtocol.h
@protocol MyProtocol
- (void)newMethod;
@end

//MyClass.h
@interface MyClass : NSObject <MyProtocol>
// The interface of the class, including the methods declared in the protocol
@end

//MyClass.m
@implementationMyClass
- (void)newMethod {
// Implement the logic of the new method
}
@end

5. Associated Objects

Associated objects allow you to add additional instance variables to an existing class at runtime. Although this is not a traditional way of extending a class, it can be useful in some situations.

1
2
3
4
5
6
7
8
9
10
#import <objc/runtime.h>

static char kAssociatedObjectKey;

objc_setAssociatedObject(myInstance, &kAssociatedObjectKey, @"Associated Value", OBJC_ASSOCIATION_RETAIN_NONATOMIC);

NSString *associatedValue = objc_getAssociatedObject(myInstance, &kAssociatedObjectKey);
NSLog(@"%@", associatedValue);