I'm using multiple storyboards in my app, which is considered as good practice. For example, from my FooViewController
in Main.storyboard
, when a button is tapped, I'll jump to another BarViewController
defined in Secondary.storyboard
programmatically.
Transitions among storyboards and view controllers are implemented in a separate file, e.g. Storyboards
, like the following:
// in Storyboards.m
@implementation Storyboards
+ (id)instantiateBarViewController {
UIStoryboard *storyboard = [UIStoryboard storyboardWithName:@"Secondary" bundle:nil];
return [storyboard instantiateViewControllerWithIdentifier:@"BarViewController"];
}
@end
Then in FooViewController
, I did this:
// in FooViewController.m
- (IBAction)someButtonTapped:(id)sender {
BarViewController *controller = [Storyboards instantiateBarViewController];
[self.navigationController pushViewController:controller animated:YES];
}
This works just fine. But my questions are:
- Is it necessary to cache the storyboard instance, so that everytime
instantiateBarViewController
is invoked, I do not need to re-create the storyboard? - If yes, should I cache
BarViewController
too?
To cache the storyboard (and the view controller), I could use code as the following:
// in Storyboards.m
@implementation Storyboards
+ (id)instantiateBarViewController {
static UIViewController *barViewController = nil; // Shared view controller.
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
UIStoryboard *storyboard = [self secondaryStoryboard];
barViewController = [storyboard instantiateViewControllerWithIdentifier:@"BarViewController"];
});
return barViewController;
}
+ (UIStoryboard *)secondaryStoryboard {
static UIStoryboard *storyboard = nil; // Shared storyboard.
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
storyboard = [UIStoryboard storyboardWithName:@"Secondary" bundle:nil];
});
return storyboard;
}
@end
Thanks!