Type CastingType Casting a process converting one type of object to another type of object. Every language a semantics of TypeCasting. Today we will discuss about type casting in Objective C.
E.g We have two class BaseClass and DerivedClass.
@interface BaseClass : NSObject
@property (nonatomic,strong) NSString *baseProperty;
@interface DerivedClass : BaseClass
@property (nonatomic,strong) NSString *derivedProperty;
Below are the different actions we can take on the objects of these classes and how Compiler handles the typecasting.
DerivedClass *derivedCl = [[DerivedClass alloc] init];
[derivedCl derivedMethod];[derivedCl baseMethod]; // There is perfectly normal as derivedCl is a BaseClass.
BaseClass *baseClass = derivedCl; // Ok too.
[baseClass derivedMethod]; // Error. Because compiler only knows that baseClass is a BaseClass type.
Error : No known class method for selector 'derivedMethod'
So How do we handle the above error. Here comes 'id' in play. So to avoid the above error we will use id.
id obj = derivedCl;
[obj derivedMethod]; // There will be no Compiler Error. As compiler knows derivedMethod exists. But its possible obj might not respond to it if it is not DerivedClass.
NSString *hello = @"String";
[hello derivedMethod]; //Compiler knows that NSString does not respond to methid derivedMethod.
DerivedClass *dc = (DerivedClass *)hello; // As we are casting here explicitly so Compiler thinks we know what we are doing, so now error.
[dc derivedMethod]; // No Compiler warning as we have forced compiler to think that hello is Derived Class. But there will be crash at runtime.Another way to do it.
[(id)hello derivedMethod]; // we have forced the compiler to ignore the object type by casting it inline. But it will crash at runtime.
Above are few typecasting examples that we can do with base class and derived class objects, and also highlights some use of id in typecasting.