user
user

Reputation: 3456

Accessing the top view controller from the app delegate

I need my AppDelegate to be able to obtain a pointer to my current displayed view controller (have explored visibleViewController for navigation views, but a more generic version would be better) and read the state from my object instances for use in applicationWillResignActive.

My attempt at this had me initializing new objects, and those are just empty. I need the object's state at any point in runtime.

I figure I could make a singleton class that parallels my objects, which I can call on from the app delegate, but that seems clunky and wordy. I also thought of making the view controller a delegate for AppDelegate, but that seems even worse.

I know I'm probably overlooking the obvious, but I must be wording my search wrong because I can't get clarity. I've searched Stack Overflow for 10 minutes and skimmed the view controller and appdelegate docs.

How can I access an object's property values at runtime from the app delegate?

Upvotes: 2

Views: 1060

Answers (1)

Wain
Wain

Reputation: 119031

Depending on exactly what your view controllers do and how you want your app to restore its state when reopened, the AppDelegate should have minimal involvement.

Instead you should consider having the view controllers that are appropriate observe the UIApplicationWillResignActiveNotification notification and each perform their own storage of their own state. When the app reopens, the AppDelegate just restores the root view controller, the root VC then checks if it needs to restore anything, and on in a chain until all data is restored. This keeps all of the logic and the data storage modular and segregated.

If you really:

need the object's state at any point in runtime

Then you have a different design problem and you need to break things down. The AppDelegate should be used for specific tasks, it has a role to play in applicationWillResignActive but that role should not be to manage 100% of the work that needs to be done.

Upvotes: 2

Related Questions