Saturday, May 25, 2013

Understanding the id Variable Type, Dynamic Typing, and Dynamic Binding

Objective-C is a dynamically typed language. Like Java, Objective-C permits object types  to be determined dynamically at runtime rather than statically at compile time. Objective-C accomplishes this dynamic typing using the id data type.

The id Type

The id variable is a data type that represents an object’s address. Because it’s just an address,  id can be any object, and because its type is a pointer, you don’t need to include the * symbol,  as the * symbol signifies a pointer to a specific type. For instance,

Foo * myFoo;

is a pointer to a Foo object. The compiler knows the pointer points to an address that contains
an object of type Foo. However, the following,

id myFoo;

provides no such information to the compiler. The compiler only knows that myFoo is a  pointer—the compiler knows where the pointer is pointing, but it doesn’t know the data type of what myFoo points to. Only at runtime can it be determined what myFoo actually  points to.

Dynamic Binding and Dynamic Typing

Objective-C accomplishes dynamic behavior using what’s called dynamic typing and dynamic  binding. Dynamic typing means that an object’s type is not determined until runtime. For  instance, a method that takes an id or an instance variable of type id has no way of knowing  the object’s type until the object is actually sent to the method or assigned to the instance  variable.

Dynamic binding means that the method to invoke is not determined until runtime. And,  unlike Java, Objective-C often doesn’t require casting an object to its specific data type before  being used.

Understanding Inheritance

You have already seen how Objective-C classes inherit from parent classes. In the interface,  you specify that a class inherits from another class by placing the parent’s name after the  class’s name and a colon.

@interface SimpleChild : Simple

Like any object-oriented language, Objective-C sets up classes to extend ancestors further  up its hierarchy, with new methods and instance variables. Objective-C child classes can also  redefine an ancestor’s method. But, like Java (and unlike C++), Objective-C allows a class to  inherit from only one parent; Objective-C doesn’t support multiple inheritance.

Overriding Methods

Objective-C inheritance allows overriding methods, but not instance variables. You already saw an example of overriding methods when you overrode NSObject’s dealloc, retain, and  release methods in the class Foo.

#import "Foo.h"
@implementation Foo
-(void) dealloc {
  NSLog(@"deallocating Foo....");
  [super dealloc];
}
---snip--
@end


Instead of calling NSObject’s methods, the runtime first calls Foo’s. Since Foo’s methods  also call the parent’s version of each method, the runtime looks up Foo’s inheritance hierarchy  for a version of the method until it finds NSObject’s version.

No comments:

Post a Comment