Contents
Dynamic Binding in Objective-C
Dynamic Binding in Objective-C
Dynamic binding refers to the process of linking a function call to its actual definition at runtime instead of compile time. In Objective-C, this feature allows greater flexibility and avoids the limitations of static binding, where method resolution occurs at build time. Dynamic binding is also referred to as late binding.
With dynamic binding, a specific method to execute is determined during program execution based on the object’s type. This feature is essential for enabling polymorphism, making it possible for a single method call to operate on different types of objects seamlessly.
Usage of Dynamic Binding
Dynamic binding in Objective-C allows a single method name to handle multiple types of objects. It simplifies debugging, reduces code complexity, and enhances program flexibility. All method resolution in Objective-C happens at runtime through the combination of method names and the receiving objects.
Example 1
#import
@interface Triangle : NSObject {
float area;
}
- (void)calculateAreaWithBase:(CGFloat)base andHeight:(CGFloat)height;
- (void)displayArea;
@end
@implementation Triangle
- (void)calculateAreaWithBase:(CGFloat)base andHeight:(CGFloat)height {
area = (base * height) / 2;
}
- (void)displayArea {
NSLog(@"Area of Triangle: %f", area);
}
@end
@interface Rectangle : NSObject {
float area;
}
- (void)calculateAreaWithLength:(CGFloat)length andBreadth:(CGFloat)breadth;
- (void)displayArea;
@end
@implementation Rectangle
- (void)calculateAreaWithLength:(CGFloat)length andBreadth:(CGFloat)breadth {
area = length * breadth;
}
- (void)displayArea {
NSLog(@"Area of Rectangle: %f", area);
}
@end
int main() {
Triangle *triangle = [[Triangle alloc] init];
[triangle calculateAreaWithBase:10.0 andHeight:5.0];
Rectangle *rectangle = [[Rectangle alloc] init];
[rectangle calculateAreaWithLength:8.0 andBreadth:4.0];
NSArray *shapes = @[triangle, rectangle];
id object1 = shapes[0];
[object1 displayArea];
id object2 = shapes[1];
[object2 displayArea];
return 0;
}
Output:
Area of Circle: 153.938400
Area of Square: 36.000000
Key Differences: Dynamic Binding vs Static Binding
Dynamic Binding | Static Binding |
---|---|
The method is resolved at runtime. | The method is resolved at compile time. |
Known as late binding. | Known as early binding. |
Applies to real objects. | Does not apply to real objects. |
Uses virtual functions. | Uses normal function calls. |
Supports polymorphism. | Does not support polymorphism. |
Execution is slower due to runtime resolution. | Execution is faster since it is resolved at compile time. |