Important: This document may not represent best practices for current development. Links to downloads and other resources may no longer be valid.
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
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)];
The example illustrates how dynamic Objective-C is—this feature is used pervasively in Cocoa.