Dynamic typing enables the runtime to determine the type of an object at runtime; thereby letting runtime factors dictate what kind of object is to be used in your code. This is particularly beneficial when it isn’t known in advance the type of object that needs to be assigned to a variable, such as when passing arguments to methods.
Objective-C supports both static and dynamic typing. When a variable isstatically typed, its type is specified upon variable declaration. For example, the following statement declares that the variable myAtom is a pointer to an object of type Atom.
Atom *myAtom;
With static typing, the compiler can perform type checking at compile time and thus detect type errors prior to program execution. With dynamic typing, on the other hand, type checking is performed at runtime.
Objective-C provides support for dynamic typing via the id data type. The id type is a unique Objective-C type that can hold a pointer to any type of Objective-C object, regardless of its class.
The following statement declares that the variablemyAtom is a pointer to an object of type id.
id *myAtom;
Hence, the variable myAtom may actually point to an object of type Atom, Hydrogen, and so forth—the actual type of the variable is determined at runtime.
Dynamic typing permits associations between objects to be determined at runtime rather than forcing them to be encoded in a static design. This can make it much easier to write a single method that can handle an object from any class, rather than write a different method for each class in an application.