Objective-C Dynamic Binding and Typing with the id Type

From Techotopia
Revision as of 15:13, 28 October 2009 by Neil (Talk | contribs)

Jump to: navigation, search

So far in this series of chapters covering object oriented programming with Objective-C we have focused exclusively on static class typing and binding. In this chapter we will look at concepts referred to as dynamic typing and dynamic binding and how the Objective-C id type is used in this context.

Static Typing vs Dynamic Typing

In previous chapters, when we have created an instance of a class we have done so by specifically declaring the type of object we are creating. For example, when we created an instance of our BankAccount class, we created a variable of type BankAccount to store the instance object:

        BankAccount *account1;

        account1 = [[BankAccount alloc] init];

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 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. 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 idtype 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:

        id object1;

        object1 = [[SavingsAccount alloc] init];

        [object1 setAccount: 4543455 andBalance: 3010.10];

        [object1 release];

        object1 = [[CustomerInfo alloc] init];

        [object1 displayInfo];


Dynamic Binding

Dynamic typing is about being able to dynamically assign objects of different types to a variable while the code is executing. The concept of dynamic binding involves the ability to to have the same level of flexibility when calling methods on objects.