Choosing the right storage

Persistence Mid-level Swift 5.0+ iOS 17+ Reviewed By Alok Singh

Pick the fix

Where should 20 MB of PDFs that the app can download again be stored?

Options
Hint 1 of 1

Can the app get it again?

Choose an answer, then open Show answer below to check it.

Show answer

Answer: A The Caches directory

Correct. It's not backed up, and the system may purge it when space is low.

Why not the others?
  • B UserDefaults. It's for small preferences and loads entirely into memory.
  • C The Documents directory. Documents is backed up and meant for user-created content.
  • D The Keychain. The Keychain is for small secrets.

30-second answer

Choose by data type, sensitivity, size and sync needs. UserDefaults holds small preferences. The Keychain holds secrets like tokens. SwiftData or Core Data hold structured, queryable app data; SQLite or GRDB work when you want SQL. Files hold documents and media: Documents for user content (backed up), Caches for re-downloadable data (the system may purge it). CloudKit or NSUbiquitousKeyValueStore sync across devices.

Practise saying it · 45 s. No recording, just a timer

Explain how you choose storage.

Say your answer out loud, then check which of these points you covered:

  • Prefs: UserDefaults
  • Secrets: Keychain
  • Structured: SwiftData/Core Data
  • Files by backup needs

Deep dive

Application Support is for app-created files the user doesn't see; it is backed up.

tmp can be cleared any time the app isn't running.

App Groups share a container with widgets and extensions.

Set file protection classes for sensitive files.

NeedUseNotes
Small preferencesUserDefaults / @AppStorageNot for secrets or big data
Tokens, passwordsKeychainPick an accessibility class
Structured, queryable dataSwiftData or Core DataMigrations needed for schema changes
User documentsDocuments directoryBacked up, visible in Files if enabled
Re-downloadable dataCaches directoryNot backed up, may be purged
Small synced settingsNSUbiquitousKeyValueStore1 MB total

Common mistakes

  • Storing large data or secrets in UserDefaults.
  • Putting re-downloadable caches in Documents, which fills iCloud backups.

Senior take & follow-ups

Seniors justify each choice by sensitivity, size, backup and sync.

Follow-up questions

Think of your answer first, then open the hint.

  1. Where do widget-shared files go?

    Show hint

    The App Group container.

  2. Which directories are backed up?

    Show hint

    Documents and Application Support, not Caches or tmp.

Suggest a fix if something here is wrong or out of date.