Ok, so I’m using Objective-C. Now, say I have:
TopClass : NSObject
- (int) getVal {return 1;}
MidClass : TopClass
- (int) getVal {return 2;}
BotClass : MidClass
- (int) getVal {return 3;}
I then put objects of each type into an NSMutableArray and take one out. What I want to do is run the getVal func on the appropriate object type, but when I put
id a = [allObjects objectAtIndex:0];
if ([a isKindOfClass:[TopClass class]])
{
int i;
i = [a getVal];
}
I get firstly a warning about multiple methods called getVal (presumably because the compiler can’t determine the actual object type until runtime). But more seriously I also get an error “void value not ignored as it should be” and it won’t compile.
If I don’t try and use the return from [a getVal] then it compiles fine e.g.
[a getval]; //obviously no good if I want to use the return value
It will also work if I use isMemberOfClass statements to cast the object to a class before running the function e.g.
if ([a isMemberOfClass:[BotClass]) i = [(BotClass*) a getVal];
But surely I shouldn’t have to do this to get the functionality I require? Otherwise I’ll have to put in a statement for every single subclass, and worse have to add a new line if I add a new sub class, which rather defeats the point of method overriding doesn’t it?
Surely there is a better way?
Since a BotClass is a MidClass and a MidClass is a TopClass, you could just set the type of
atoTopClass*.The better way is to add
-getValto the@interfaceand#importit. Then the compiler will know such this method is likely to return anintand won’t complain even ifais anid. Make sure the method name won’t coincide with others, though.(BTW, in ObjC, getters won’t be named as
-getFoo. The convention is just call it-foo.)