How to cast 'Class A' to its subclass 'Class B' - Objective-C

nrj picture nrj · Aug 6, 2009 · Viewed 34.6k times · Source

I'm using a framework which defines and uses 'ClassA', a subclass of NSObject. I would like to add some variables and functionality so naturally I created 'ClassB', a subclass of 'ClassA'

Now my problem is this. Many of the methods within this framework return instances of 'ClassA' which I would like to cast to my subclass.

For example take this method:

- (ClassA *)doSomethingCool:(int)howCool

Now in my code I try this:

ClassB * objB;
objB = (ClassB *)doSomethingCool(10); 

NSLog(@"objB className = %@", [objB className]);

This runs just fine. No compile or runtime errors or anything. But what is really odd to me is the output:

>> "objB className = ClassA"

The casting obviously failed. Not sure what's happened at this point... objB is typed as 'ClassB', but it's className is 'ClassA' and it won't respond to any 'ClassB' methods.

Not sure how this is possible... Anyone know what I am doing wrong here?

I found a similar post which is exact opposite of what I'm asking here

Answer

Chuck picture Chuck · Aug 6, 2009

Casting object variables in Objective-C is usually a mistake (there are a few cases where it's right, but never for this sort of thing). Notice that you aren't casting an object — you're casting a pointer to an object. You then have a pointer of type ClassB*, but it still points to the same instance of ClassA. The thing pointed to hasn't changed at all.

If you really want to convert instances of ClassA to ClassB, you'll need to write a ClassB constructor method that can create a ClassB instance from a ClassA. If you really need to add instance variables, this might be your best choice.

As Jason said, though, it's often a good idea to try a category first.