Wednesday, May 18, 2016

Objective-C Dynamic Binding

Before discussing Dynamic Binding, I suggest you to go through my post 
Objective C Dynamic Typing, which is on Dynamic Typing in Objective C.

We use id If we are not sure about the data type we need to hold.

Dynamic binding is determining the method to invoke at runtime instead of at compile time. Dynamic binding is also referred to as late binding. In Objective-C, all methods are resolved dynamically at runtime. The exact code executed is determined by both the method name (the selector) and the receiving object.


Let's discuss this concept by taking a real time use case.

Dynamic Binding mainly comes into picture when we have similar kind of objects with similar functionality. Let's say we have Students and Teachers. All these objects comes under a base class called Person though their job is different and they do have most of similar functionalities.

Let's say they have to start performing well. And we have received couple of these classes objects who are not performing well and we need to call that action on those objects.

NSArray *arr = [NSArray arrayWithObjects: student1, teacher1, student4, teacher7];

 id person1 = [arr objectAtIndex:0];
 id person2 = [arr objectAtIndex:3];

 [person1 startPerformingWell];     // student1 has to start studying well.
 [person2 startPerformingWell];     // teacher7 has to improve his/her teaching skills

We don't know whether it is a Student object or a Teacher Object. So we have dynamically typed it using the id type.

When we call startPerformingWell action on those id objects based on the method name and the receiving object, the respective method will get called at run time. Which is called Dynamic Binding or Late Binding. That's how Dynamic Binding enables Polymorphism.

Hope this post is useful. Feel free to comment in case of any queries.