Note that there are some explanatory texts on larger screens.

plurals
  1. POPolymorphic variable in Objective-C
    text
    copied!<p>Let's say I have a class named <code>Parent</code> and two derived classes called <code>Child1</code> and <code>Child2</code>.</p> <pre><code>@interface Parent : NSObject { NSString *fooVariable; -(void)foo; } @end @interface Child1 : Parent { -(void)bar1; } @end @interface Child2 : Parent { -(void)bar2; } @end </code></pre> <p>Now imagine I have a method called <code>foo</code> and in some cases I want to pass it as a parameter an instance of <code>Child1</code> and in some other cases an instance of <code>Child2</code>. Depending on the class type I want to call either method <code>bar1</code> or <code>bar2</code>.</p> <p>How can I achieve this in Objective-c? </p> <p><strong>What I've tried:</strong></p> <p>I decided to use the following signature and implementation:</p> <pre><code>-(void)fooWithObject:(Parent *)instance{ if ([instance isKindOfClass:[Child1 class]]){ [instance bar1]; } else{ [instance bar2]; } } </code></pre> <p>So now I can do this:</p> <pre><code>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] </code></pre> <p>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. </p> <p>According to a some tutorials online you can do the following, so theoretically my approach should work:</p> <pre><code>NSArray *anotherArray = [NSMutableArray array]; // This mutable-only method call is valid but // produces a compile-time warning [anotherArray addObject:@"Hello World"]; </code></pre>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload