What is the app container, and why must you never persist an absolute path?

6.1.2 · L2 · Interview

Predict first

What should you store to find a file again after the next launch?

// A: the absolute path string
// B: the file name or relative path, rebuilt against the current container
// C: the container’s UUID
  • A
  • B
  • C

Mental model. The street address of your flat is reassigned whenever you move in again. You tell people which flat number to ask for, and look the address up fresh each time.

The sandbox gives every app two containers. The bundle container holds the signed .app (read-only). The data container holds everything the app writes: Documents, Library (with Caches, Preferences and Application Support) and tmp. Apps that share an app group also get a group container. You find these through FileManager APIs, never by hard-coding a path.

The reason is that the container’s location contains a generated identifier that can change: reinstalling the app, restoring from a backup to another device, or (for the bundle) updating it, can give you a new path. A saved absolute path then points at nothing. Store a relative path or file name and rebuild the full URL from FileManager.urls(for:in:) on each launch. The sandbox also means you cannot see another app’s files, and that Bundle.main is read-only: writable data belongs in the data container, with the right folder chosen as in the file-directories question.

The container location can change, so persist only the part that is yours and recompute the base with FileManager.

Common traps

  • Saving a URL or path string in UserDefaults. After a reinstall or restore it is stale. Save a relative name.
  • Writing into the bundle. It is signed and read-only; the write fails.

They might follow up with

  • Where do app-group files live? In a separate group container returned by containerURL(forSecurityApplicationGroupIdentifier:).
  • Which folders are backed up? Documents and Application Support; Caches and tmp are not. See the file-directories question.

Related questions

  • 2.3.6 Where should an iOS app put files: Documents, Application Support, Caches or tmp?
  • 6.8.1 What is an app group, and what can go wrong when an app and an extension share a database?
  • 6.1.1 What is the iOS process model, and what can an app process not do?

← What is the iOS process model, and what can an app process not do?   What are entitlements, and what happens when they do not match the… →