Saturday, 17 August 2013

Polymorphic variable in Objective-C

Polymorphic variable in Objective-C

Let's say I have a class named Parent and two derived classes called
Child1 and Child2.
@interface Parent : NSObject {
NSString *fooVariable;
-(void)foo;
}
@end
@interface Child1 : Parent {
-(void)bar1;
}
@end
@interface Child2 : Parent {
-(void)bar2;
}
@end
Now imagine I have a method called foo and in some cases I want to pass it
as a parameter an instance of Child1 and in some other cases an instance
of Child2. Depending on the class type I want to call either method bar1
or bar2.
How can I achieve this in Objective-c?
What I've tried:
I decided to use the following signature:
-(void)fooWithObject:(Parent *)instance;
So now I can do this:
Parent *instance = [[Child1 alloc] init];
//This call is supposed to lead to an invocation of bar1 inside the foo
method
[self fooWithObject:instance]
instance = [[Child2 alloc] init];
//This call is supposed to lead to an invocation of bar2 inside the foo
method
[self fooWithObject:instance]
Unfortunately, when I try to compile my code the compiler complains that
there's is no method bar1 (or bar2) declared in my Parent's interface.

No comments:

Post a Comment