Objective-C Dynamic Binding and Typing with the id Type

From Techotopia
Jump to: navigation, search
PreviousTable of ContentsNext
Pointers and Indirection in Objective-CObjective-C Variable Scope and Storage Class

Purchase the full edition of this Objective-C book in Print ($14.99) or eBook ($12.99) format
Objective-C 2.0 Essentials Print and eBook (ePub/PDF/Kindle) editions contain 31 chapters.

Buy Print

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];

<google>IOSBOX</google> 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 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 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 = [[CustomerInfo alloc] init];

[object1 displayInfo];

Dynamic Binding

Dynamic typing is about using the id type to provide a variable that can be used to store objects of any type during program execution. Dynamic binding takes this one step further by allowing methods on an object stored in an id variable to be called without prior knowledge of the type of object currently assigned to the variable.

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).

Let's begin by writing our function:

void objDisplay (id object)
{
        [object displayInfo];
}

As we can see from the above code, the function is called objDisplay, it accepts an object as the single argument which is assigned to an id type variable, and then makes a call to the displayInfo method of the object. We can now combine this function with a main routine that creates two different object types and then calls the objDisplay function for each:

int main (int argc, const char * argv[])
{
   @autoreleasepool {

        id object1;

        object1 = [[SavingsAccount alloc] init];

        [object1 setAccount: 4543455 andBalance: 3010.10];

        objDisplay (object1);

        object1 = [[CustomerInfo alloc] init];

        objDisplay (object1);
    }
    return 0;
}

Note that the objDisplay function makes the assumption that the object it has been passed actually has a method named displayInfo. This highlights a shortcoming of dynamic typing and binding in that the compiler will be unable to warn you of any errors such as attempting to call a non-existent method on a dynamically typed object variable. The problem will only become apparent when the program is running. If, for example, the CustomerInfo class lacked a displayInfo method, the program would terminate in the objDisplay method with an error similar to:

*** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '*** 
-[CustomerInfo displayAccountInfo]: unrecognized selector sent to instance 0x104cc0'

This brings us to the subject of polymorphism.


Polymorphism

Polymorphism is the ability to have methods with the same name in different classes. For example both our SavingsAccount and CustomerInfo classes in the above examples have displayInfo methods. Whilst the code and resulting output displayed is different for each method they both ultimately achieve the same result (i.e. displaying the values assigned to the encapsulated instance variables). Polymorphism is a key concept in providing a consistent programming interface to the classes you create in your program. If all the classes have a method that performs a similar task then programming convention dictates that they should be given the same names. This helps both in writing code to work with objects and also with the use of dynamic binding.

Purchase the full edition of this Objective-C book in Print ($14.99) or eBook ($12.99) format
Objective-C 2.0 Essentials Print and eBook (ePub/PDF/Kindle) editions contain 31 chapters.

Buy Print



PreviousTable of ContentsNext
Pointers and Indirection in Objective-CObjective-C Variable Scope and Storage Class