With iOS 6 Apple added state restoration to UIViewController
and related classes. This allows the application to save state when terminated and restore it when the user resumes the application.
Everything seems to work fine, however I have reached a weird scenario which doesn't want to fit into the pattern.
Let's assume we have two view controllers, ViewControllerOne
and ViewControllerTwo
, both of them store some arbitrary state that is restored successfully. Now let's imagine that ViewControllerOne
has a delegate
property and that ViewControllerTwo
is that delegate (which is a common pattern for modal view controllers). Who is responsible for restoring this relationship? And how is it supposed to be stored/restored?
In my particular case no storyboards are involved, the restoration happens in code, via the restorationClass
property. My first instinct was to try and restore the relationship whilst creating the view controller in the restorationClass, however as the restorationClass
has no idea of other existing controllers it can't quite restore such a relationship.
Alternatively, if it is the view controller that declares the delegate
property, that is supposed to restore the relationship, then how does it now of the controller instance that was restored in some other class?
In short, this seems like a poorly documented scenario and I was hoping someone could shed some light on it.
I would say, the task falls on the delegate view controller to set itself as such, just like you do it before pushing the other view controller.
On how you can accomplish this, you have several options.
You can store a weak reference to your view controllers in a globally accessible location (for example, the app delegate), and use these values in
application:didDecodeRestorableStateWithCoder:
to set the delegation - this is what this method is for in the API.Alternatively, you could post a "hereIAmThisIsMe" notification (with
self
part of the user info) from the top view controller to which the delegate listens and sets itself as a delegate.