How can viewControllerWithRestorationIdentifierPath:coder: find an existing instance?
Asked Answered
N

1

10

The docs on viewControllerWithRestorationIdentifierPath:coder: say:

Your implementation of this method should create (or find) the corresponding view controller object and return it... It is not always necessary to create a new view controller object in your implementation of this method. You can also return an existing view controller object that was created by another means. For example, if the view controller had already been loaded from a storyboard file, you would return that object rather than create a new one. [My italics.]

This has always seemed like complete nonsense to me. This is a class method! We don't have any access to any instances at this moment — unless we create one. I'd be grateful if someone can explain to me how on earth a class method can find or know about "the view controller that has already been loaded from a storyboard file".

EDIT: To earn the bounty you must show me an actual case, from your own app, of the class method viewControllerWithRestorationIdentifierPath:coder: being used to "return an existing view controller object that was created by another means."

Nursemaid answered 2/9, 2013 at 23:38 Comment(0)
D
2

The most common example of this I can think of is any of the view controllers that are owned by the App Delegate. This is traditionally a tab bar controller or a navigation controller in traditional apps, but sometimes it can be something completely custom, which is when this functionality might be useful.

Since the UIApplication is pretty much a singleton and has one delegate, it means your App Delegate has global state, which makes it accessible from anywhere, including in class methods with: [[UIApplication sharedApplication] delegate].

Of course, any singleton is accessible from anywhere and a common pattern (but one I personally dislike) is to have a NavigationManager singleton which manages any global view controller transitions, so in this case you'd be able to access the existing instances as well.

Diffident answered 2/9, 2013 at 23:55 Comment(1)
In real life, since the app delegate is indeed probably the one who knows what view controllers have already been loaded from the storyboard file and how to refer to them as the restoration mechanism kicks in, it seems more likely that I'd skip viewControllerWithRestorationIdentifierPath:coder: and use the app delegate's application:viewControllerWithRestorationIdentifierPath:coder: instead. And since this is an instance method, there's no problem. I seem to have failed to elicit any circumstances where one wouldn't do that.Nursemaid

© 2022 - 2024 — McMap. All rights reserved.