Object Typing

Dynamic Binding

All objects are allocated in the heap (in memory), and this is why we always use pointers.

When we give a pointer a type, we say that it is statically typed. In the following example,

aString is a statically typed pointer to an NSString.

id, which we’ve seen before as the return type of - (id)init is a non-statically typed pointer. We could alternatively write the following:

id is useful when the pointer type can vary. This is the case with - (id)init, which is often called by subclasses. This is also the case when using collections like NSArray and NSDictionary because they can hold different types of objects and keys.

Even though it’s perfectly valid to use id anytime, it makes more sense to statically type our pointers, especially when we know their type.

Attempts to call methods on objects always happen at runtime, never at compile time. Static typing allows the compiler to find bugs, and it will generate errors when methods called on objects aren’t found.

Casting and Typing

Let’s look back at our animals.

Header Source


We can find out information on objects before calling methods that might not be valid. This is done using methods defined in the root NSObject class.

- (BOOL)respondsToSelector:(SEL)aSelector
Returns whether or not the object implements or inherits a method that can respond to a specified message.

When referencing selectors, we have to use the @selector(...) directive, which turns the name of a method into a selector.

We can also use the SEL type to create a variable for our selector.

- (BOOL)isKindOfClass:(Class)aClass
Returns whether or not the object is an instance of the given class, or an instance of any class that inherits from it.

- (BOOL)isMemberOfClass:(Class)aClass
Returns whether or not the object is an instance of the given class (excluding its subclasses).

The previous code generates the following output.

Comments are closed.