Changes

Jump to: navigation, search

Objective-C Dynamic Binding and Typing with the id Type

8 bytes added, 19:40, 19 November 2009
no edit summary
</pre>
Because we have pre-declared the type of object that is to be assigned to the ''account1'' variable we have performed something called ''static typing''. This is also sometimes referred to as ''compile time'' typing because we have provided enough information for the compiler to check for errors during the complication compilation process.
Often when writing object oriented code we won't always know in advance what type of object might need to be assigned to a variable. This is particularly true when passing objects through as arguments to functions or methods. It is much easier to write a single, general purpose function or method that can handle an object from any class, than to write a different function or method for each class in an application. This is where the concept of ''dynamic typing''is used. Dynamic typing allows us to declare a variable that is capable of storing any type of object, regardless of its class origins. This is achieved using the Objective-C ''id'' type. The ''id''type is a special, general purpose data type that can be assigned an object of any type.
In the following dynamic typing example, we create a variable of type ''id'' named ''object1'' and then assign a ''BankAccount'' object to it. We then call a method on the object before releasing it. We then use the same object1 variable to store an object of type ''Customer Info'' and call a method on that object:
Suppose, for example, that we want to write a function that is passed an object. Within the function the ''displayInfo'' method of that object is called. Without dynamic typing and dynamic binding we would need to write one function for each class type that we wanted to be able to handle. With Objective-C's dynamic typing and binding we can declare the object argument as being type ''id'', thereby allowing us to pass any object through to the function. Secondly, we can then rely on dynamic binding to ensure that when we call the object's ''displayInfo'' method within the function, we are calling it on the correct object (i.e. the one that was passed through as an argument).
Lets Let's begin by writing our function:
<pre>

Navigation menu