MontiRabbit
MontiRabbit

Reputation: 1030

Get StoryBoard from ViewController identifier

I'm working with 3 storyBoards and in a section of code I get the identifier of a ViewController but can't call instantiateViewControllerWithIdentifier because I dont know which storyBoard belongs to it.

The question is: Is it possible to get the StoryBoard instance/identifier using the ViewController identifier?

Best regards!

Upvotes: 1

Views: 5328

Answers (3)

user1459524
user1459524

Reputation: 3603

I have researched a similar problem for days for my app. As far as I know, it's not possible to find out if a storyboard contains a specific viewcontroller id. Apple's docs expect you to know this beforehand, and if an id is not found, it immediately raises an exception.

I have seen suggestions to use try-catch blocks. Having played around with them, I find that treading on pretty thin ice, though, and if you have multiple storyboards to test against, it quickly gets quite convoluted IMO.

One approach I took in my app is to come up with a naming scheme for the viewcontrollers which basically includes the info to which storyboard it belongs. For example, all viewcontrollers in storyboard 1 would start with "1-...". You can then extract this in the code via string functions, and instantiate the correct storyboard on the fly.

Upvotes: 0

Javier Chávarri
Javier Chávarri

Reputation: 1615

You can call instantiateViewControllerWithIdentifier but you will get a nil value returned if the view controller with that identifier does not exist.

You could test this way on your three storyboards until you find a value different than nil.

See Apple documentation

Edited: after detecting the exception (sorry, Apple docs are a bit confusing sometimes), what you can do is wrap you code with a try/catch block like this

    @try {
        UIViewController *myViewController = [[UIStoryboard storyboardWithName:@"MainStoryboard" bundle:nil] instantiateViewControllerWithIdentifier:@"myViewControllerID"];
    }
    @catch (NSException *exception) {
        DLog(@"Exception: This is not the storyboard");
    }
    @finally {
        DLog(@"I found it!");
    }

Upvotes: 2

Janusz Chudzynski
Janusz Chudzynski

Reputation: 2710

I had similar problem with my app. Multiple view controllers and multiple storyboards. I just use the name of storyboard that contains my view controller and create new instance of it. And than I am instantiating a new view controller from that storyboard.

UIStoryboard * st =  [UIStoryboard storyboardWithName:@"storyboardWithViewControllerName" bundle:nil];
YourViewController * vc =   [st instantiateViewControllerWithIdentifier:@"YourViewControllerId"];

Hope it helps

Upvotes: 1

Related Questions