Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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

like image 246
nrj Avatar asked Aug 06 '09 00:08

nrj


People also ask

How do you typecast in Objective C?

It should be noted here that the cast operator has precedence over division, so the value of sum is first converted to type double and finally it gets divided by count yielding a double value.

How do you know if a class B is subclass of class A?

Python issubclass() is built-in function used to check if a class is a subclass of another class or not. This function returns True if the given class is the subclass of given class else it returns False . Return Type: True if object is subclass of a class, or any element of the tuple, otherwise False.


1 Answers

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.

like image 168
Chuck Avatar answered Sep 22 '22 11:09

Chuck