3

I have an AnimalViewController. It it a base view controller. I also have the AnimalViewController Scene in UIStoryBoard.

I have a question about inheritance.

@interface BearViewController : AnimalViewController
@interface LionViewController : AnimalViewController

Is it possible to instantiate BearViewController with AnimalViewController Scene?

PS BearViewController and LionViewController have the same interface as AnimalViewController.

Voloda2
  • 12,359
  • 18
  • 80
  • 130

2 Answers2

2

The solution is to use xib instead storyboard.

BearViewController *bearVC = [[BearViewController alloc] initWithNibName:@"Animal" bundle:nil];
LionViewController *lionVC = [[LionViewController alloc] initWithNibName:@"Animal" bundle:nil];
Voloda2
  • 12,359
  • 18
  • 80
  • 130
  • [The strategy pattern is an another way for this problem.](http://stackoverflow.com/a/17381927/419348) – AechoLiu Jan 20 '16 at 02:40
-1

You can you do the following but I don't think storyboards were designed to do something like this, you will still be having AnimalViewController object just casted to subclass so basically you will gain nothing (except different pointer type) and get runtime crashes when you call any of BearViewController defined methods later:

BearViewController *bearViewController = [storyboard instantiateViewControllerWithIdentifier:@"AnimalViewController"];

[[self navigationController] pushViewController:bearViewController animated:YES];
Tomasz Zabłocki
  • 1,326
  • 7
  • 14
  • The cast doesn't change the actual runtime object. It simply tells the compiler to "trust you"... that the object returned at runtime will be a BearViewController. If the scene is configured to be an AnimalViewController, that's what will be returned at runtime... So the code you've written doesn't instantiate a BearViewController. – J Shapiro Oct 26 '12 at 11:26
  • This is exactly what I meant... it gives you nothing except different pointer type. – Tomasz Zabłocki Oct 26 '12 at 11:29
  • The question was about how to instantiate BearViewController. This answer does not address that. – Eric Dec 14 '12 at 06:11