Persistence with Core Data
Core Data is Apple's framework for saving your app's objects on the device. You'll meet the NSManagedObjectContext , define entities , run fetch requests , drive a live list with @FetchRequest , and save changes.
Learn Persistence with Core Data in our free Swift course — a beginner-friendly interactive lesson with worked examples, a practice exercise and a quick…
Part of the free Swift course at LearnCodingFast — hands-on lessons with examples you run in your browser, plus practice exercises and a quick quiz.
What You'll Learn in This Lesson
- • What the NSManagedObjectContext is and why it matters
- • How entities describe the shape of stored objects
- • Insert objects and persist them with save()
- • Query data with NSFetchRequest and fetch
- • Filter and sort with NSPredicate and sort descriptors
- • Build a live SwiftUI list with @FetchRequest
📊 Core Data Vocabulary
Term
Meaning
Entity
Blueprint for a kind of object
NSManagedObject
An instance of an entity
Context
Scratchpad of unsaved changes
NSFetchRequest
A query for objects
save()
Write changes to disk
1️⃣ Insert and Save
You create objects inside a context , set their attributes, then call save() to persist them. Nothing reaches disk until you save.
2️⃣ Fetch Requests
An NSFetchRequest describes what to load. Attach an NSPredicate to filter and sort descriptors to order, then call context.fetch(request) .
Your turn. Fill in the request type and the fetch method.
3️⃣ @FetchRequest in SwiftUI
In SwiftUI, @FetchRequest loads managed objects and keeps the view in sync — add or delete an object and the list updates automatically.
Now you try. Fill in the delete and save methods.
Pro Tips
- 💡 Save deliberately. Batch related edits, then call save() once.
- 💡 Generate NSManagedObject subclasses so you use typed properties instead of setValue(forKey:) .
- 💡 Use predicates to filter in the store, not in Swift — it's far faster on large data.
- 💡 Let @FetchRequest drive the UI so the list refreshes itself.
Common Errors (and the fix)
- Changes vanish after relaunch — you forgot try context.save() .
- "entity not found" — the entity name string doesn't match your .xcdatamodeld exactly.
- Crash on background access — only use viewContext on the main thread.
- List doesn't refresh — you fetched manually; prefer @FetchRequest so SwiftUI observes changes.
📋 Quick Reference
Task
Code
Result
Get context
container.viewContext
a workspace
Save
try context.save()
writes to disk
Build query
NSFetchRequest(entityName:)
a request
Run query
try context.fetch(request)
objects
Delete
context.delete(object)
marks removal
SwiftUI
@FetchRequest(...)
live results
Frequently Asked Questions
Mini-Challenge: Tiny Task Store
Create a Task, save it, then fetch the unfinished ones with a predicate and print their names.
🎉 Lesson Complete!
- ✅ The NSManagedObjectContext tracks changes before saving
- ✅ Entities describe the shape of stored objects
- ✅ save() writes pending changes to disk
- ✅ Query with NSFetchRequest + fetch , filtered by NSPredicate
- ✅ @FetchRequest drives a live SwiftUI list
- ✅ Next lesson: SwiftData Basics — the modern successor on iOS 17+
Practice quiz
What is Core Data primarily used for?
- Drawing UI
- Persisting and managing an object graph on the device
- Making network calls
- Animating views
Answer: Persisting and managing an object graph on the device. Core Data manages and persists a graph of model objects locally.
What does an NSManagedObjectContext represent?
- A scratchpad for creating, editing, and saving managed objects
- A network session
- A SwiftUI view
- A JSON decoder
Answer: A scratchpad for creating, editing, and saving managed objects. The context is the in-memory workspace where you make and track changes before saving.
In Core Data, an 'entity' is most like...
- A function
- A thread
- A table or class describing a kind of object
- A URL
Answer: A table or class describing a kind of object. An entity defines the structure (attributes) of a type of stored object.
Which type do you use to query for objects?
- URLRequest
- NSFetchRequest
- JSONDecoder
- DispatchQueue
Answer: NSFetchRequest. NSFetchRequest describes what objects to fetch and how to filter/sort them.
Which method actually fetches results from a context?
- context.save()
- context.delete()
- context.reset()
- context.fetch(request)
Answer: context.fetch(request). context.fetch(request) executes a fetch request and returns the matching objects.
How do you persist changes to disk?
- context.commit()
- context.save()
- context.flush()
- context.write()
Answer: context.save(). Calling save() on the context writes pending changes to the persistent store.
Which property wrapper loads and observes Core Data results in SwiftUI?
- @FetchRequest
- @State
- @Published
- @Binding
Answer: @FetchRequest. @FetchRequest fetches managed objects and keeps the view updated as data changes.
To refine which objects a fetch returns, you set its...
- timeout
- statusCode
- predicate (NSPredicate)
- scheme
Answer: predicate (NSPredicate). An NSPredicate on the fetch request filters which objects match.
How do you remove a managed object?
- context.delete(object)
- object.remove()
- context.drop()
- object = nil
Answer: context.delete(object). context.delete(object) marks it for deletion; save() makes it permanent.
An NSPersistentContainer mainly provides...
- A view hierarchy
- A network layer
- A JSON encoder
- The Core Data stack including the context and store
Answer: The Core Data stack including the context and store. NSPersistentContainer sets up and holds the Core Data stack for you.
Continue this course
- Previous: Networking with URLSession & async/await
- Next: SwiftData Basics