iOS Persistence Standards
Priority: P0
Implementation Guidelines
SwiftData (iOS 17+)
- •Models: Use
@Modelmacro for pure Swift classes. - •Container: Use
ModelContainerfor schema management. Inject into the environment for SwiftUI apps. - •Queries: Use
@Queryfor declarative data fetching in Views.
Core Data (Standard)
- •Persistent Stack: Initialize
NSPersistentContainerin a dedicatedPersistenceController. - •Context Management: Use
viewContextfor UI tasks andnewBackgroundContext()for heavy imports to avoid blocking the main thread. - •FetchedResultsController: Use
NSFetchedResultsControllerfor efficient list management with change tracking.
Best Practices
- •Migration: Always perform lightweight migrations for minor schema changes. Use versioned models for complex migrations.
- •Threading: Managed objects are not thread-safe. Always access them on the context's queue (e.g.,
perform { ... }). - •Batching: Use
NSBatchUpdateRequestorNSBatchDeleteRequestfor large datasets.
Anti-Patterns
- •Main Thread Blocking:
**No heavy I/O on ViewContext**: Use private background contexts. - •Manual String Keys:
**No string-based predicates**: Use KeyPaths or generated helpers. - •Missing Merge Policies:
**No merge strategy**: Explicitly set mergePolicy (e.g., mergeByPropertyObjectTrump).