Retired Document
Important: This document may not represent best practices for current development. Links to downloads and other resources may no longer be valid.
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.
Copyright © 2018 Apple Inc. All Rights Reserved. Terms of Use | Privacy Policy | Updated: 2018-04-06