Reuse UIViewController instances when using storyb

2019-03-13 08:07发布

I decided to give the use of storyboards a go in my current iPhone app. I am facing a bit of a problem. I really need to reuse my UIViewController instances.

What do I mean by that? Well, for example I have a table view controller. When I tap a cell, another view controller is loaded from the storyboard and pushed onto the navigation controller stack. This all works well, but it takes about half a second to a second each time this view controller is loaded. Before I was using story boards I simply solved this problem by caching the created instance so the second time you tap a cell the view controller can be immediately shown.

By caching the created instance I mean something like this:

if (!cachedInstance) {
    cachedInstance = [MyViewController new];
}
[self.navigationController pushViewController:cachedInstance];

Does anyone know how to accomplish this using the storyboard? Thanks in advance.

1条回答
Lonely孤独者°
2楼-- · 2019-03-13 08:53

If you are using segues, you will need to create custom segues in order to use a cached view controller like you did before. Otherwise, the typical "push" segue will create a new instance of the view controller for segue.destinationViewController. If you write a custom UIStoryboardSegue class and use custom segues you can override initWithIdentifier:source:destination: and put your cached view controller in for the destinationViewController, and then override perform to use the classic pushViewController call.

That is how you handle the segue if you are really intent on using them. I would just skip it though, unless you really want the fancy arrows to lay everything out on your storyboard. If you skip it you can just instantiate the view controllers into the cache and then push them on just like you did before.

If your question is more about locating a view controller inside a storyboard then you can use:

UIViewController *vc = [[UIStoryboard storyboardWithName:@"MainStoryboard" bundle:nil] instantiateViewControllerWithIdentifier:@"Some View Controller"];

Then you can save that to your cache and push it like you did in your example code.

Hope that helps.

查看更多
登录 后发表回答