Home > DeveloperSection > Articles > Objective-C : Dynamic Binding

Objective-C : Dynamic Binding


iPhone iPhone  Ios  Objective C 
Ratings:
0 Comment(s)
 832  View(s)
Rate this:


Objective-C : Dynamic Binding     





Previously we learn uses of attributes of @property directive : Objective-C : Attributes of @property Directive

 

Dynamic Binding: Dynamic bindingAlso called "late binding," it is the linking of a routine or object at runtime based on the conditions at that moment.  Dynamic Binding takes one step further to Dynamic typing allowing methods to be called on Dynamic typed variable. In other words, it allows to call a method on variable without enforcing the Datatype of that variable.


Let us look at a simple code that would explain dynamic binding.


#import< Foundation/Foundation.h>

 

@interface Square:NSObject

{

   float area;

}

- (void)calculateAreaOfSide:(CGFloat)side;

- (void)printArea;

@end

 

@implementation Square 

- (void)calculateAreaOfSide:(CGFloat)side

{

    area = side * side;

}

- (void)printArea

{

    NSLog(@"The area of square is %f",area);

} 

@end

 

@interface Rectangle:NSObject

{

   float area;

}

- (void)calculateAreaOfLength:(CGFloat)length andBreadth:(CGFloat)breadth;

- (void)printArea;

@end

 

@implementation  Rectangle 

- (void)calculateAreaOfLength:(CGFloat)length andBreadth:(CGFloat)breadth

{

    area = length * breadth;

}

- (void)printArea

{

    NSLog(@"The area of Rectangle is %f",area);

} 

@end

 

int main()

{

   Square *square = [[Square alloc]init];

   [square calculateAreaOfSide:10.0];

   Rectangle *rectangle = [[Rectangle alloc]init];

   [rectangle calculateAreaOfLength:10.0 andBreadth:5.0];

   NSArray *shapes = [[NSArray alloc]initWithObjects: square, rectangle,nil];

   id object1 = [shapes objectAtIndex:0];

   [object1 printArea];

   id object2 = [shapes objectAtIndex:1];

   [object2 printArea];

   return 0;

}

Now when we compile and run the program, we will get the following result.

2015-07-18 06:35:29.687 demo[12539] The area of square is 100.000000

2015-07-18 06:35:29.688 demo[12539] The area of Rectangle is 50.000000

 

As you can see in the above example, printArea method is dynamically selected in runtime. It is an example for dynamic binding and is quite useful in many situations when dealing with similar kind of objects.

 


Don't want to miss updates? Please click the below button!

Follow MindStick