L12: Persistence and Error Handling in iOS

Sep 5, 2024

Lecture 12: Persistence in iOS

Introduction

  • Persistence: Making data stay on devices across app closures, restarts, etc.
    • Local persistence (on device)
    • Future topics: Persistence on the internet

Local Persistence in iOS

  • Various methods:
    • Unix file system
    • SQL databases
    • Core Data (object-oriented on top of SQL)
    • iCloud and CloudKit
    • Third-party network storage options
    • User defaults for lightweight data

Focus on Unix File System and User Defaults

  • Unix File System:
    • iOS uses Unix file system with sandboxing for security, privacy, cleanup, and backup.
    • Sandbox directories:
      • Application directory (read-only)
      • Documents directory (user documents)
      • Application Support (user data)
      • Caches (non-backed-up data)
  • URLs:
    • Accessing and manipulating file paths
    • Creating URLs for file system access
    • Using URL and Data structs for reading/writing

Auto-saving in EmojiArt

  • Implement auto-save feature for EmojiArt document
  • Use JSONEncoder to encode models as JSON data
  • Handle errors with do-catch blocks
  • Implement saving and loading from file system

User Defaults

  • Persistent key-value storage for lightweight data
  • Set and get values using keys
  • Use Data and JSON to store more complex data
  • Handle key naming to avoid conflicts across app

Error Handling in Swift

  • Functions marked with throws can throw errors
  • Must use try to call such functions
  • Methods for handling errors:
    • Ignore with try?
    • Crash with try!
    • Propagate with throws
    • Handle with do-catch

Property Wrappers

  • Purpose: Encapsulate behavior for class variables
  • Common Property Wrappers:
    • @State: Keeps state in the heap, causes view updates when state changes
    • @Published: Notifies changes via objectWillChange.send
    • @ObservedObject: Observes changes in observable objects
    • @Binding: Binds a variable to a source of truth
    • @Environment: Access app environment values

Using Bindings

  • Ensure single source of truth
  • Pass data between views with bindings
  • Common in text fields, toggles, and UI updates

Conclusion

  • Introduction to persistence and error handling
  • Understanding property wrappers and bindings

This lecture covered critical concepts in persistence, error handling, and property wrappers, laying the groundwork for creating robust iOS applications. The next lecture will focus on complex UI development with multiple views.