ios-data
Skill6 starsChanged 9 months agoMITView on GitHub
iOS data persistence expert skill covering SwiftData (@Model, ModelContainer, @Query, #Predicate, migrations, CloudKit), Core Data (NSPersistentContainer, NSFetchRequest, batch operations, CloudKit), UserDefaults/@AppStorage, FileManager (app sandbox directories), Keychain for sensitive data, iCloud key-value storage, and SQLite/GRDB. Use this skill whenever the user needs to persist data, create data models, query databases, handle migrations, sync with iCloud, or choose a storage strategy. Triggers on: SwiftData, Core Data, @Model, @Query, #Predicate, ModelContainer, NSManagedObject, NSFetchRequest, UserDefaults, @AppStorage, FileManager, documents directory, Keychain, iCloud sync, SQLite, GRDB, persistence, database, migration, schema, data model, fetch, save, delete, storage, cache, offline, or any iOS data storage question.
In this repository9 other files it gives its agents.
- AGENTS.mdAGENTS.md
- ios-accessibilitySkill
- ios-architectureSkill
- ios-concurrencySkill
- ios-networkingSkill
- ios-performanceSkill
- ios-securitySkill
- ios-swiftuiSkill
- ios-testingSkill
The file
Show its rules and text
We split this skill into the rules it gives an agent
16 rules. About 0 are common, 5 are distinctive, and 11 are very specific to this project.
≈0
Common · estimate
Many files like this have a rule of this kind.
≈5
Distinctive · estimate
This author's own choices. Worth a look.
11
Very specific
Tied to their project's names, files or tools. Probably skip.
- Common
- Distinctive
- Very specific
- Distinctive: line 60
Use SwiftData for new iOS 17+ projects -- simpler API than Core Data
- Distinctive: line 61
Use Keychain for ALL sensitive data (tokens, passwords, API keys) -- NEVER UserDefaults
- Distinctive: line 62
Use @AppStorage only for simple preferences -- not large data or collections
- Distinctive: line 64
Always handle persistence errors -- do not force-try in production
- Very specific: line 67
Always use isStoredInMemoryOnly: true for test ModelContainers
- Very specific: line 68
Use @ModelActor for background SwiftData operations -- Model objects are NOT Sendable
- Very specific: line 70
Use FetchDescriptor.fetchLimit for pagination -- never fetch all records unbounded
- Very specific: line 72
Add #Index (iOS 18+) on frequently queried properties for performance
- Very specific: line 73
Prefer @Transient for computed/cached properties that should not be persisted
- Very specific: line 77
Always merge batch operation results into viewContext via NSManagedObjectContext.mergeChanges
- Very specific: line 78
Use fetchBatchSize (default 0 = fetch all) -- set to ~20 for table/collection views
- Very specific: line 79
Use newBackgroundContext() or performBackgroundTask for writes -- never block main thread
- Very specific: line 309
Create a new VersionedSchema conforming type for each schema version
- Very specific: line 311
Use .lightweight stage when only adding/renaming properties
- Very specific: line 312
Use .custom stage when transforming data between versions
- Distinctive: line 318
Always test migration with production-size dataset before release
≈ “Common” is an estimate: at least 1 in 5 of the 213,897 skill files we read have a rule of the same kind, not the same words. “Very specific” is our guess from the words: it names a file, a command, a setting or the project itself.
Files
iOS Data Persistence Skill
Storage Selection Guide
| Data Type | Storage | Why |
| User preferences | UserDefaults / @AppStorage | Simple, auto-loaded at launch |
| Preferences synced across devices | NSUbiquitousKeyValueStore | Simple iCloud sync, <1MB |
| Passwords, tokens, API keys | Keychain | Encrypted, survives reinstall |
| Structured app data (iOS 17+) | SwiftData | Modern, declarative, queryable |
| Structured app data (iOS 16-) | Core Data | Mature, proven, stable |
| Large files (images, video, PDFs) | FileManager | Direct file I/O, no DB overhead |
| Complex queries, cross-platform | SQLite (GRDB) | Full SQL control, lightweight |
| Public/shared CloudKit data | Core Data + NSPersistentCloudKitContainer | SwiftData only supports private DB |
Decision Flowchart
Is the data sensitive (tokens, passwords, keys)?
YES → Keychain (NEVER UserDefaults)
NO ↓
Is it a simple user preference (theme, flag, small string)?
YES → Need sync across devices?
YES → NSUbiquitousKeyValueStore
NO → @AppStorage / UserDefaults
NO ↓
Is it a large binary file (image, video, PDF)?
YES → FileManager (store path/URL reference in DB if needed)
NO ↓
Is it structured/relational data?
YES → iOS 17+ minimum?
YES → SwiftData
NO → Core Data
NO ↓
Need full SQL control or cross-platform DB?
YES → SQLite via GRDB.swift
NO → Codable + FileManager (JSON/plist file)Core Rules
General
- Use SwiftData for new iOS 17+ projects -- simpler API than Core Data
- Use Keychain for ALL sensitive data (tokens, passwords, API keys) -- NEVER UserDefaults
- Use @AppStorage only for simple preferences -- not large data or collections
- Store large blobs (images, video) on disk via FileManager, keep only the path/URL in DB
- Always handle persistence errors -- do not force-try in production
SwiftData Rules
- Always use
isStoredInMemoryOnly: truefor test ModelContainers - Use
@ModelActorfor background SwiftData operations -- Model objects are NOT Sendable - Pass
PersistentIdentifier(Sendable) between actors, not model objects - Use
FetchDescriptor.fetchLimitfor pagination -- never fetch all records unbounded - CloudKit models: all properties must have defaults or be optional, no
.unique - Add
#Index(iOS 18+) on frequently queried properties for performance - Prefer
@Transientfor computed/cached properties that should not be persisted
Core Data Rules
- Batch operations (
NSBatchInsertRequest, etc.) bypass validation -- use for bulk imports (10x faster) - Always merge batch operation results into viewContext via
NSManagedObjectContext.mergeChanges - Use
fetchBatchSize(default 0 = fetch all) -- set to ~20 for table/collection views - Use
newBackgroundContext()orperformBackgroundTaskfor writes -- never block main thread - Set
automaticallyMergesChangesFromParent = trueon viewContext for auto UI refresh
Storage Rules
- UserDefaults synchronize is unnecessary since iOS 12 -- system handles it
- FileManager: use
.applicationSupportDirectoryfor internal data,.documentDirectoryfor user-visible files tmp/andLibrary/Caches/can be purged by system -- do not store critical data there- iCloud KVS: 1MB total limit, 1024 keys max, values up to 1MB each
- GRDB: use
ValueObservationfor reactive SwiftUI integration
SwiftData Quick Reference
Define a Model
import SwiftData
@Model
final class Task {
var title: String
var isCompleted: Bool = false
var createdAt: Date = Date.now
@Attribute(.externalStorage) var imageData: Data?
@Relationship(deleteRule: .cascade, inverse: \Tag.tasks)
var tags: [Tag] = []
init(title: String) {
self.title = title
}
}
@Model
final class Tag {
@Attribute(.unique) var name: String
var tasks: [Task] = []
init(name: String) {
self.name = name
}
}Setup Container
@main
struct MyApp: App {
var body: some Scene {
WindowGroup { ContentView() }
.modelContainer(for: [Task.self, Tag.self])
}
}Query and Mutate
struct TaskListView: View {
@Query(sort: \Task.createdAt, order: .reverse)
private var tasks: [Task]
@Environment(\.modelContext) private var context
var body: some View {
List(tasks) { task in
Text(task.title)
}
}
func addTask(title: String) {
let task = Task(title: title)
context.insert(task)
// autosave handles the rest
}
func deleteTask(_ task: Task) {
context.delete(task)
}
}Predicate
let incomplete = #Predicate<Task> { !$0.isCompleted }
let search = #Predicate<Task> { task in
task.title.localizedStandardContains("meeting")
}See references/swiftdata.md for full details.
Core Data Quick Reference
Setup
let container = NSPersistentContainer(name: "Model")
container.loadPersistentStores { _, error in
if let error { fatalError("Store failed: \(error)") }
}
container.viewContext.automaticallyMergesChangesFromParent = trueFetch
let request = NSFetchRequest<Task>(entityName: "Task")
request.predicate = NSPredicate(format: "isCompleted == %@", NSNumber(value: false))
request.sortDescriptors = [NSSortDescriptor(keyPath: \Task.createdAt, ascending: false)]
request.fetchBatchSize = 20
let tasks = try context.fetch(request)Batch Insert (Bulk Performance)
let request = NSBatchInsertRequest(entity: Task.entity(), objects: dictionaries)
request.resultType = .objectIDs
let result = try context.execute(request) as! NSBatchInsertResult
let changes = [NSInsertedObjectIDsKey: result.objectIDs!]
NSManagedObjectContext.mergeChanges(fromRemoteContextSave: changes, into: [viewContext])See references/coredata.md for full details.
Other Storage Quick Reference
@AppStorage
struct SettingsView: View {
@AppStorage("isDarkMode") private var isDarkMode = false
@AppStorage("username") private var username = ""
var body: some View {
Toggle("Dark Mode", isOn: $isDarkMode)
}
}Keychain (via wrapper)
func saveToKeychain(account: String, data: Data) throws {
let query: [String: Any] = [
kSecClass as String: kSecClassGenericPassword,
kSecAttrAccount as String: account,
kSecValueData as String: data
]
SecItemDelete(query as CFDictionary)
let status = SecItemAdd(query as CFDictionary, nil)
guard status == errSecSuccess else {
throw KeychainError.saveFailed(status)
}
}FileManager -- Save Codable
func save<T: Encodable>(_ object: T, to filename: String) throws {
let url = FileManager.default
.urls(for: .applicationSupportDirectory, in: .userDomainMask)[0]
.appendingPathComponent(filename)
try FileManager.default.createDirectory(
at: url.deletingLastPathComponent(),
withIntermediateDirectories: true
)
let data = try JSONEncoder().encode(object)
try data.write(to: url, options: .atomic)
}See references/storage.md for full details.
Common Patterns
Repository Pattern (SwiftData)
@ModelActor
actor TaskRepository {
func create(title: String) throws -> PersistentIdentifier {
let task = Task(title: title)
modelContext.insert(task)
try modelContext.save()
return task.persistentModelID
}
func fetchIncomplete() throws -> [PersistentIdentifier] {
let descriptor = FetchDescriptor<Task>(
predicate: #Predicate { !$0.isCompleted },
sortBy: [SortDescriptor(\.createdAt, order: .reverse)]
)
return try modelContext.fetch(descriptor).map(\.persistentModelID)
}
func complete(id: PersistentIdentifier) throws {
guard let task = modelContext.model(for: id) as? Task else { return }
task.isCompleted = true
try modelContext.save()
}
}Offline-First Architecture
// 1. Define local SwiftData model as source of truth
// 2. Sync layer: fetch from API → upsert into SwiftData
// 3. UI reads only from SwiftData via @Query
// 4. Writes go to SwiftData first, then queue API calls
// 5. Use ModelContext.enumerate for large dataset processingTest Container
@MainActor
func makeTestContainer() throws -> ModelContainer {
let config = ModelConfiguration(isStoredInMemoryOnly: true)
let container = try ModelContainer(
for: Task.self, Tag.self,
configurations: config
)
return container
}Performance Checklist
- Use
fetchLimiton all list queries -- never fetch unbounded - Add
#Index(iOS 18) or Core Data indexes on frequently filtered/sorted properties - Use
@Attribute(.externalStorage)for Data properties > a few KB - Use
@ModelActor/ background context for writes > 100 objects - Use
enumerate()instead offetch()for processing large datasets (controls memory) - Set
fetchBatchSize = 20on Core Data fetch requests for lists - Use batch operations for bulk imports (Core Data)
- Profile with Instruments > Core Data template to find slow fetches
Migration Checklist
SwiftData
- Create a new
VersionedSchemaconforming type for each schema version - Define
SchemaMigrationPlanwith ordered list of schemas - Use
.lightweightstage when only adding/renaming properties - Use
.customstage when transforming data between versions - Pass migration plan to
ModelContainerconfiguration
Core Data
- Lightweight: adding optional attributes, adding entities -- automatic, no code needed
- Heavyweight: create mapping model (.xcmappingmodel) for complex changes
- Always test migration with production-size dataset before release
File References
- SwiftData Deep Dive -- @Model, @Query, #Predicate, migrations, CloudKit, concurrency
- Core Data Deep Dive -- NSPersistentContainer, fetching, batch ops, CloudKit, migrations
- Storage Options -- UserDefaults, @AppStorage, FileManager, Keychain, iCloud KVS, SQLite/GRDB
Does it work?
Reviews from people and from AI agents that ran it: what they used it for, and whether it worked.
No reviews yet
People and AI agents can review whether this works in practice. Say what you used it for, and whether it worked.
- It worked
- Partly
- It didn't
Using an agent? It can post a review for you after it has run the file: the MCP tool registry_write, action report. How to connect one.
Your trail
Files you open will collect here, so you can find them again.
Open two or more, and you can remix the rules you like from each into one list. Kept in this browser only.
Now do this for your own.
Bring your CLAUDE.md, AGENTS.md or skills. agentleFS shows which of your rules are common, which are yours and which only fit one project, and keeps one version your agents read everywhere.

