Typecasting in Objective-C

Posted: April 7, 2011 in Did you know?, Objective-C

Hey all, I decided to add a new section to my blog (for developers) where we can share some tips and tricks on computer languages, design patterns, code patterns, architecture and any trends that may be of consequence to mobile and next generation device (endpoints).

So here we go, the first one:

Objective C would say - never mind till you follow a hierarchy

In Objective C , you can always cast a pointer to an instance of one class to a pointer to an instance of its superclass implicitly. This works for indirect superclasses as well. For example: NSMutableArray is a subclass of NSArray, which is a subclass of NSObject. You can cast an NSMutableArray to NSArray or NSObject. Casting in opposite direction, however, requires an explicit cast.

For those who are new to type casting, converting an expression (general term used for structs / objects and more) of a given type into another type is known as type casting. In a number of languages implicit conversions are limited to standard types where the risk of losing data precision is minimal, acceptable. C++ is an example of a strongly typed language. Objective C, on the other hand, relaxes the rule slightly. Layout of any object is defined by the instance variables (ivars) in the root class, then by the instance variables in each subsequent class down the hierarchy. Subclasses can only add new instance variables, not remove or rearrange ones from the superclasses. this means that it is always safe, in terms of memory layout, to cast a pointer to an instance of one class to a pointer to an instance of another. From OOP point of view, this means any subclass will always respond to all of the messages that the superclass responds to. Pretty neat hmm.

Objective-C also introduces a new pointer type: id. This is roughly analogous to void*, when it comes to casting rules. You may cast any object pointer to type id any you may cast id to any object pointer type, implicitly.

Historically when Smalltalk was conceived, intent was to define a general purpose language on a single sheet of paper. Objective-C inherits a number of its features from Smalltalk. In short it adds Objects to C.

A word of caution: In most circumstances, type of objects you are dealing with is already known. If you not dealing with generating structures / objects on the fly, avoid casting (implicit or explicit), too much of cumbersome class hierarchies and the damn polymorphism. Remember any operation that the runtime needs to do for you adds up and in the embedded world, each operation is worth dollars and pounds.

Any cool examples of Typecasting are welcome!

Advertisement
Comments
  1. mobisynth says:

    What’s up tringers? No one can take on Typecasting?

  2. Siddhesh Naik says:

    Type casting has always been one of the worst night mare for a new developer. A concept, if clear, can help you to understand many things. And if not clear, can shoot you in the foot.

    In C, wrong type casting was one of the main reason for the “SEG FAULT” error. An error, some times, hard to trace. C allowed basic type casting. One of the golden rules for type casting was to follow the hierarchy of data types: double, float, long, int, short, char.
    A pointer to double can point to long data, and so forth.

    In Objective C, type casting is about using a pointer of the sub type to point to an object of its parent type.

    Type casting allows us to use a single pointer to point to multiple instances of the current or the super class, depending on the program flow. Its there for the flexibility it provides.
    But before using this flexibility, we need to have a good understanding of the problem it might create, if not implemented properly.

    E.g. when we use the type “id” in a code, the runtime spends time in figuring out the exact type of the object. Then for some wired reason, if the object type goes wrong, and we pass a wrong message to that object, the app crashes.

    My take on type casting:
    1. The code size of majority mobile apps are small. In most of the situation we know what the object type is. Avoid using type casting in such places.
    2. Give a proper thought before using type casting. If we use it, and are not sure about the runtime behavior, use certain checks before sending a message to the object. e.g. check if the object responds to a message or not.

  3. Ramesh says:

    Type Casting or Type Conversion is used when you want to changes values from one type to another.

    Type Conversion can be performed either implicitly or explicitly
    Implicit Conversions
    Some type conversions are inherently safe and are allowed to occur automatically, without any conversion code required. When you’re converting between scalar types, some conversions are guaranteed to succeed.
    For example, scalar types such as short, int, and long differ only in the range of values they can store. A short value can always be stored in an int, and an int can always be stored in a long, without writing any conversion code, as shown here:

    short s = 32767; int n = s;

    Explicit Conversions

    Conversions that result in a loss of data require you to write code that explicitly demands that a conversion take place.
    Many times, a conversion that might result in a loss of data is actually harmless. For example, a conversion from a double to a float results in a loss of precision in your application, however, the degradation in precision might be a harmless conversion. A value stored as a long can be safely converted to an int if you know that its value will always fall into the range permitted for an int.

    To explicit convert from one type to another, we may require to use the cast operator. To use the cast operator, you enclose the new type in parentheses and place it to the left of the value to be cast, as shown here:
    int longVal = 32767; short s = (short)longVal;

    In any case, it is always better to have the casting statements inside a try catch block to catch any type cast error at runtime.

  4. Ramesh says:

    Objective C introduces a new pointer type: id. This id type is very useful when the type of the variable is known at runtime and not at compile time.

    But we have to be very careful, while accessing any properties or methods of the id type variable.

    We may be accessing some method of the object assuming that the variable contains object of type A while it contains object of some other type. We will get a runtime error at this time.

    To avoid such kind of errors, we may use object’s IsKindOfClass method to determine whether the object is of a specific type and accordingly proceed with the remaining statements based on the result.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Connecting to %s