Nov 16, 2012
Class cast
If you want to get rid of all these nasty isKindOfClass:
if ([something isKindOfClass:[A class]]) {
A * aPtr = (A*)something;
// Do things with aPtr...
}
you may wish to use class_cast:
// class_cast.h file
// class_cast returns pointer to a specified type or nil
template<typename T> T * class_cast(NSObject * o) {
if ([o isKindOfClass:[T class]]) {
return (T*)o;
}
return nil;
}
Somewhere in your project (make sure you are using a C++ compiler – don’t forget to use “.mm” file extension):
// Foo.mm file
// Templates are available only in C++ - make sure to use ".mm" extension.
#include "class_cast.h"
...
if (A * aPtr = class_cast<A>(something)) {
// Do something with aPtr
}
// or even
[class_cast<A>(something) doSomething];
// (cause we can send messages to nil)
I’m not sure if I did invent this trick or I snatched it somewhere; anyway, you may use it. For free 😉

