tezvyn:

iOS State Preservation: Resume Where You Left Off

AI-drafted, machine-checkedSource: developer.apple.comadvanced
iOS State Preservation: Resume Where You Left Off

Think of it as an automatic bookmark for your app's UI. When iOS terminates your app, state preservation can save the user's place, restoring the view hierarchy on next launch.

WHY IT EXISTS: iOS aggressively terminates backgrounded apps to preserve battery and memory for the foreground app. Without state preservation, a user deep in a navigation stack would be kicked back to the home screen on the next launch, creating a jarring and frustrating experience. State preservation solves this by making termination less noticeable to the user.

THE MENTAL MODEL: State preservation is like a "save game" feature for your app's UI, triggered by the operating system. When the system is about to terminate your app, it quickly takes a snapshot of the navigation path. On the next launch, it uses this snapshot to rebuild the UI exactly as it was. It's about restoring the user's path, not the app's data.

HOW IT WORKS: The process is opt-in. You enable it in your AppDelegate. Then, for each view controller you want to save, you assign a restorationIdentifier. When the app is backgrounded, the system traverses the view controller hierarchy and asks each opted-in controller to encode its state. On relaunch, the system decodes this archive to rebuild the view hierarchy. You are responsible for restoring the underlying data models yourself.

WHEN TO USE IT: Use it in any app with a non-trivial navigation structure. It's essential for document-based apps, apps with deep drill-down UIs like settings or e-commerce catalogs, or any app where losing your place after a short break would be annoying for the user.

WHEN NOT TO USE IT: Never rely on it for saving critical user data; that's the job of Core Data, UserDefaults, or other persistence methods. State restoration is for UI state only. It's also less critical for simple, single-screen apps where the user always starts from a clean slate.

ONE CANONICAL EXAMPLE: A user is editing a contact, three screens deep. They switch to another app. iOS terminates the contacts app. Later, they tap the app icon. Instead of seeing the main contact list, the app opens directly to the edit screen for that same contact. This is because the navigation controller and its children had restoration identifiers and encoded their state before termination.

Read the original → developer.apple.com

Get five bites like this every day.

Tezvyn delivers a daily feed of 60-second tech bites with quizzes to lock in what you learn.