Dynamic binding

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.

Dynamic binding enables polymorphism. For example, consider a collection of objects including Dog, Athlete, and ComputerSimulation. Each object has its own implementation of a run method. In the following code fragment, the actual code that should be executed by the expression [anObject run] is determined at runtime. The runtime system uses the selector for the method run to identify the appropriate method in whatever the class of anObject turns out to be.

NSArray *anArray = [NSArray arrayWithObjects:aDog, anAthlete, aComputerSimulation, nil];
id anObject = [anArray objectAtIndex:(random()/pow(2, 31)*3)];
[anObject run];

The example illustrates how dynamic Objective-C is—this feature is used pervasively in Cocoa.

Prerequisite Articles

Related Articles

    (None)

Definitive Discussion