【发布时间】:2015-06-23 23:43:53
【问题描述】:
我在我的应用中使用了多个故事板,这被认为是一种很好的做法。例如,在Main.storyboard 中的FooViewController 中,当点击按钮时,我会以编程方式跳转到Secondary.storyboard 中定义的另一个BarViewController。
情节提要和视图控制器之间的转换在单独的文件中实现,例如Storyboards,如下:
// in Storyboards.m
@implementation Storyboards
+ (id)instantiateBarViewController {
UIStoryboard *storyboard = [UIStoryboard storyboardWithName:@"Secondary" bundle:nil];
return [storyboard instantiateViewControllerWithIdentifier:@"BarViewController"];
}
@end
然后在FooViewController,我这样做了:
// in FooViewController.m
- (IBAction)someButtonTapped:(id)sender {
BarViewController *controller = [Storyboards instantiateBarViewController];
[self.navigationController pushViewController:controller animated:YES];
}
这很好用。但我的问题是:
- 是否需要缓存storyboard实例,这样每次调用
instantiateBarViewController就不需要重新创建storyboard? - 如果是,我是否也应该缓存
BarViewController?
要缓存故事板(和视图控制器),我可以使用如下代码:
// 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
谢谢!
【问题讨论】:
-
这对我来说似乎是过早优化的情况。
-
我会采用不同的方法并使用:github.com/rob-brown/RBStoryboardLink 它允许您直观地链接故事板。非常强大的工具
-
@AshleyMills 我对此也有疑问,这就是为什么我在我的应用程序中实现它之前在 SO 中提出这个问题的原因。 ;-)
-
@SimonMcLoughlin 感谢您的链接。我也知道这个项目,但我更喜欢使用手动方式来做到这一点。因为:1)我认为代码会更容易理解; 2) 正如该项目所述:“RBStoryboardLink 最初是作为概念验证的,现在基本上仍然如此。” -- 但如果您认为我的手动方法与 RBStoryboardLink 相比存在严重缺陷或明显劣势,我很高兴知道并切换到 RBStoryboardLink。
标签: ios objective-c cocoa-touch storyboard