iOS - access class method using targets

111 views Asked by At

I have the following code:

UIStoryboard *storyboard = [UIStoryboard storyboardWithName:@"MyViewController" bundle:nil];
UINavigationController *navControllerInstance = [storyboard instantiateViewControllerWithIdentifier:NSStringFromClass([MyViewController class])];

When I use targets my problem is [MyViewController class] is returning "MyTarget_2.MyViewController" then my app crash because "'Storyboard (<UIStoryboard: 0x600001e65d80>) doesn't contain a view controller with identifier "

I have two targets: MyTarget and MyTarget_2 and is only failing with the last one.

I don't understand is why [MyViewController class] is returning MyTarget.MyViewController. When I start a new project this is not happening, only returns MyViewController . Why is such a difference?

This seems to be related because I'm using swift+objective-c Calling NSStringFromClass on a Swift Class in Objective-C returns module mangled name

3

There are 3 answers

1
Jayesh Thanki On

You can get class name like this :

NSString *className = [[NSStringFromClass([MyViewController class]) componentsSeparatedByString:@"."] lastObject];
UIStoryboard *storyboard = [UIStoryboard storyboardWithName:@"MyViewController" bundle:nil];
UINavigationController *navControllerInstance = [storyboard instantiateViewControllerWithIdentifier:className];

and make sure that your storyboard id should be MyViewController

1
Tej On

Did you give Identifier to your ViewController in storyboard ?

You can give it against Storyboard ID in ViewController's identify Inspector section.

Because ,

UINavigationController *navControllerInstance = [storyboard instantiateViewControllerWithIdentifier:NSStringFromClass([MyViewController class])];

method work on the identifier and not on class name

3
B25Dec On

I think you haven't copied that particular storyboard in to your target. You can verify it. Click on target. Then on Build Phase -> Copy bundle resource. Check if storyboard file exist in both targets. And if storyboard is not there click on + button add that file. Clean and run. Hope it help.