skip to content

Core Data

Core Data manages an object graph and persists it, usually to SQLite, through contexts and fetch requests. Interviewers use it to test whether you see past the database-wrapper myth.

on this pageshow

explore

questions

page 1 of 2

In Core Data, how do you build an NSFetchRequest for one region's bird sightings, newest first, and what does executing it return?

level: juniorimportance: must knowfreq 80%

answer

  1. entity, predicate, sort descriptors
  2. the request's generic result type
  3. sort descriptor array order matters
  4. fetch(_:) throws, returns a typed array
  5. unsaved inserts can match too

basics

~20 s

Create an NSFetchRequest<Sighting> for the entity, set a predicate such as region == %@ and an NSSortDescriptor on the date, descending, then call the context's fetch(_:), which throws or returns a [Sighting] array, empty when nothing matches.

solid answer

~40 s

A fetch request names the entity, through `NSFetchRequest<Sighting>(entityName: "Sighting")` or the generated subclass's `fetchRequest()`. I add a `predicate`, here `NSPredicate(format: "region == %@", region)`, and `sortDescriptors`, which apply in array order: date descending first, species ascending to break ties. Leave them out and the request specifies no order, so never rely on the one you happen to see. `fetchLimit` caps the result when the screen needs only the first fifty. `try context.fetch(request)` returns `[Sighting]` registered with that context, or throws; no match gives an empty array. Each execution goes to the persistent store, and it also matches against the context's unsaved inserts, edits and deletes, so the result reflects what that context holds right now.

code

swift · 19 lines
swift
import CoreData

@objc(Sighting)
final class Sighting: NSManagedObject {
    @NSManaged var species: String
    @NSManaged var region: String
    @NSManaged var seenAt: Date
}

func recentSightings(in region: String, context: NSManagedObjectContext) throws -> [Sighting] {
    let request = NSFetchRequest<Sighting>(entityName: "Sighting")
    request.predicate = NSPredicate(format: "region == %@", region)
    request.sortDescriptors = [
        NSSortDescriptor(keyPath: \Sighting.seenAt, ascending: false),
        NSSortDescriptor(keyPath: \Sighting.species, ascending: true)
    ]
    request.fetchLimit = 50
    return try context.fetch(request)   // [Sighting], empty when nothing matches
}

go deeper

for a junior

Build the request from memory: entity name, predicate with %@, sort descriptors in priority order, then try context.fetch(_:) and handle an empty array as a normal result.

for a middle

Explain what the fetch sees: the store on every run, plus the context's unsaved inserts, edits and deletes through includesPendingChanges, and why sort descriptor order decides ties.

for a senior

Show you size requests to the screen, setting fetchLimit for short lists and knowing it only saves disk work on the SQL store, and that a default refetch keeps pending edits.

for a principal

Frame it as a team convention: typed requests, key-path sort descriptors and named request builders per screen, so reviewers can see what each screen reads and how much.

## What a fetch request is An **`NSFetchRequest`** is a description of search criteria: which **entity** to read, which objects of it to keep, in what order, and how many. It does nothing on its own; a **managed object context** executes it against the persistent stores behind that context's coordinator and hands back the results. In Swift the class is generic, `NSFetchRequest<ResultType>`, and the type parameter says what comes back: `Sighting` for managed objects, `NSManagedObjectID`, `NSDictionary` or `NSNumber` for the other result types. For a bird-watching log, the screen "sightings in the North region, newest first" is one request. ## Building the request 1. **Name the entity.** `NSFetchRequest<Sighting>(entityName: "Sighting")` works everywhere. Xcode's generated subclass also has a `fetchRequest()` class method already typed to `NSFetchRequest<Sighting>`; `NSManagedObject`'s own `fetchRequest()` returns the untyped `NSFetchRequest<NSFetchRequestResult>`, which is why Swift code usually annotates or uses the generated one. 2. **Filter with a predicate.** `request.predicate = NSPredicate(format: "region == %@", region)`. With no predicate the request returns every instance of the entity, subject to the other settings. The syntax of predicates is a lesson of its own. 3. **Order with sort descriptors.** `sortDescriptors` is an array of `NSSortDescriptor`, applied **in array order**: the first decides, the second breaks ties, and so on. `NSSortDescriptor(keyPath: \Sighting.seenAt, ascending: false)` is the type-checked form; `NSSortDescriptor(key: "seenAt", ascending: false)` is the string form. A `nil` array means no sort descriptors and therefore no defined order. 4. **Cap it if the screen needs only a few.** `fetchLimit = 50` returns at most fifty objects. Apple's documentation calls the limit a best effort and singles out the SQL store: every other store type runs the full fetch and discards the extra rows. 5. **Execute it.** `try context.fetch(request)` on the context the screen reads from. Which context that is, and which queue it runs on, is covered in the lesson on managed object contexts. ## What comes back | Situation | Result of `fetch(_:)` | |---|---| | Matches exist in the store | `[Sighting]`, each registered with the context | | Nothing matches | an empty array, not `nil` | | Unsaved insert in this context matches | included in the array | | Object edited in memory so it now matches | included, judged on its in-memory values | | Object deleted in the context but not saved | excluded | | The request is invalid | the call throws | Two behaviours surprise people: - **Every execution reaches the persistent store.** A fetch request does not answer from a cache of previous results; Apple's documentation says it always accesses the underlying stores for the latest results. - **By default, a fetch does not overwrite what you already hold.** If an object is already realised in the context, or carries unsaved changes, a new fetch that includes it returns that same instance with its current in-memory state, not fresh values from disk. Setting `shouldRefreshRefetchedObjects = true` asks the fetch to update fetched objects' property values from the store instead. The **`includesPendingChanges`** property, `true` by default, is what makes unsaved changes count. Set it to `false` and the request matches only what the store holds. ## Executing directly Since iOS 10 a request can also run itself with `try request.execute()`, which uses the context associated with the current queue. Its header comment says it must be called from within a block submitted to a managed object context, so in practice it lives inside `perform`. Calling `context.fetch(_:)` is the more explicit choice and the one most code reviews expect. ## Mistakes worth avoiding - Relying on whatever order an unsorted fetch happens to produce. - Treating an empty array as an error, or expecting `nil` for "no matches". - Assuming unsaved objects are invisible to a fetch, then inserting duplicates. - Expecting a second fetch to discard edits the context has not saved. - Fetching every object to show the first few rows instead of setting `fetchLimit`. - Building the same request in five view controllers; a small function per screen, like the one in the example, keeps entity name, predicate and sort order in one reviewed place. - Sorting with a string key that does not exist on the entity; the key-path form `\Sighting.seenAt` lets the compiler catch the typo. The objects that come back are usually **faults** whose data is loaded on first access; how and when those faults fire belongs to the lesson on relationships and faulting.

  • Does fetch(_:) return a Sighting you inserted into the context but have not saved yet?
    Yes, if it matches. `includesPendingChanges` defaults to `true`, so the fetch also evaluates the context's unsaved inserts, judges edited objects on their in-memory values and leaves out objects deleted but not yet saved. Setting it to `false` matches only what the persistent store holds. Dictionary results are the exception: they always reflect the store.
  • When would you call execute() on the request instead of context.fetch(_:)?
    `execute()`, added in iOS 10, runs the request against the context tied to the current queue, and its header says it must be called from within a block submitted to a managed object context, typically inside `perform`. It returns the same kind of array. `context.fetch(_:)` names the context explicitly, which makes the code easier to review, so it is the usual choice.
  • You fetch a sighting, edit its species without saving, then run the same fetch again; what do you get?
    The same instance with your unsaved edit still in it. By default a fetch does not replace the in-memory state of objects that are already realised or carry pending changes; it hands back the existing objects. Seeing the stored values again means discarding the edit, for example with the context's `rollback()`, or refreshing the object.

  • Without sort descriptors, results come back in insertion order.
  • A fetch only sees saved data, so unsaved inserts are never returned.
  • fetch(_:) returns nil when nothing matches the predicate.
  • Sort descriptors are applied together, so their order in the array does not matter.
  • fetchLimit makes every store type read fewer rows from disk.
  • By default, running the fetch again replaces unsaved edits with the stored values.
open as a page

In Core Data's model editor, what do the Class Definition, Category/Extension and Manual/None codegen settings generate for an entity, and when do you pick each?

level: juniorimportance: must knowfreq 66%

basics

~10 s

Class Definition generates the NSManagedObject subclass and its @NSManaged properties at build time; Category/Extension generates only the properties extension and you write the class; Manual/None generates nothing, so you own both files.

open as a page

In Core Data, how do you model a Course with many Lessons and Students taking many Courses, and why give each relationship an inverse?

level: juniorimportance: must knowfreq 72%

basics

~20 s

Give Lesson a to-one course and Course a to-many lessons, set each as the other's inverse, and pair Student.courses with Course.students for many-to-many. With inverses set, Core Data updates the other side whenever you change one.

open as a page

In Core Data, what does NSPersistentContainer build for you, and what must happen before its viewContext can save?

level: juniorimportance: must knowfreq 75%

basics

~10 s

NSPersistentContainer loads the managed object model it is named after, builds the persistent store coordinator and a main-queue viewContext. Nothing persists until loadPersistentStores(completionHandler:) has added each store description and reported every store's error.

open as a page

In Core Data, which queues do viewContext and a newBackgroundContext() context run on, and how do perform(_:), performAndWait(_:) and the async perform differ?

level: middleimportance: must knowfreq 78%

basics

~20 s

viewContext is a main-queue context for the UI; newBackgroundContext() returns a new private-queue context for imports. perform(:) queues a block and returns, performAndWait(:) blocks until it ends, and async perform suspends and returns its result.

open as a page

In Core Data, how do you write the NSPredicate for a species search-as-you-type filtered by region and dates, and why never interpolate the typed text?

level: middleimportance: must knowfreq 75%

basics

~20 s

Pass every value as an argument: species CONTAINS[cd] %@ for the text, region IN %@ for regions and seenAt >= %@ AND seenAt < %@ for dates, joined by NSCompoundPredicate. Interpolated text breaks parsing, and an apostrophe crashes the app.

open as a page

In Core Data, how do model versions and NSPersistentContainer's default store options let an app update add an attribute without losing data?

level: middleimportance: must knowfreq 60%

basics

~20 s

Add a new model version, make it current and never edit a shipped one. At load Core Data compares the store's version hashes with the current model, and NSPersistentContainer enables automatic migration and mapping inference by default, so an added optional attribute migrates.

open as a page

In Core Data, why does a non-optional String attribute generate a String? property, while an optional Integer 16 attribute generates a plain Int16?

level: middleimportance: must knowfreq 58%

basics

~20 s

Core Data's Optional box is a save-time validation rule, not the Swift type. Object attributes generate Swift optionals because they can be nil before save; scalars generate plain numbers, so an unset optional Int16 reads 0.

open as a page

In Core Data, which delete rules make deleting a Course remove its Lessons but keep its Students, and what does each rule do?

level: middleimportance: must knowfreq 70%

basics

~20 s

Set Course.lessons to Cascade and Course.students to Nullify. Nullify clears the deleted object from the other side, Cascade deletes the destination objects too, Deny refuses the delete while destinations exist, and No Action changes nothing on the other side.

open as a page

In Core Data, what is a fault, what makes one fire, and what does isFault tell you about a fetched Student?

level: middleimportance: must knowfreq 66%

basics

~20 s

A fault is a managed object, or a relationship, whose values Core Data has not loaded into it yet. Reading a persistent property fires it. isFault true means the object is still a placeholder; false means its data is in memory.

open as a page

In Core Data unit tests, how do you build a fresh stack for every test, and when is NSInMemoryStoreType the wrong store type?

level: middleimportance: must knowfreq 60%

basics

~10 s

Create a new NSPersistentContainer per test from one shared model, with an NSInMemoryStoreType description or a SQLite store at /dev/null. The in-memory type cannot run SQLite-only work such as batch requests; /dev/null SQLite can.

open as a page

Your Core Data expense app crashes now and then after a background import passes fetched Expense objects to the dashboard; why, and how do you catch and fix it?

level: seniorimportance: must knowfreq 66%

basics

~20 s

Managed objects are bound to their context's queue, so reading private-queue Expense objects on the main thread is a data race that crashes or corrupts data at random. Run with -com.apple.CoreData.ConcurrencyDebug 1 to trap it, and pass NSManagedObjectIDs instead.

open as a page

In Core Data, a 30,000-sighting list opens slowly and uses a lot of memory, and each region badge fetches every object to count it; how do you fix both?

level: seniorimportance: must knowfreq 60%

basics

~20 s

Set fetchBatchSize to about two screens of rows, so Core Data records every matching identity but loads row data in batches through a proxy array, and replace fetch-then-count with context.count(for:), which returns the number without creating any managed objects.

open as a page

In Core Data, a 600-student roster stutters while scrolling because each cell shows the student's courses and their teachers; why does every row hit the store, and how do you fix it?

level: seniorimportance: must knowfreq 62%

basics

~20 s

Each cell traverses student.courses and course.teacher, and each relationship fault fires its own store query as the row appears. Set relationshipKeyPathsForPrefetching to ["courses", "courses.teacher"] so Core Data loads them per batch in a few queries.

open as a page

In Core Data, how does a child context make an expense edit sheet cancellable, and what does saving that child context actually write?

level: middleimportance: should knowfreq 55%

basics

~20 s

Give the sheet a context whose parent is viewContext and load the expense into it by objectID. Cancel just discards that child. Saving the child only pushes its changes into viewContext; nothing reaches the store until viewContext saves too.

open as a page

In Core Data, how does NSFetchedResultsController feed a list of sightings grouped by bird family, and what makes it report changes?

level: middleimportance: should knowfreq 65%

basics

~20 s

Give NSFetchedResultsController a sorted fetch request, the view context and sectionNameKeyPath family, call performFetch(), then read sections and object(at:). Once its delegate implements a change callback, such as the snapshot method, it tracks that context and reports every change.

open as a page

In Core Data, version 2 renames Album's title attribute to name; why do titles vanish after lightweight migration, and how does a renaming identifier keep them?

level: middleimportance: should knowfreq 48%

basics

~20 s

An inferred mapping pairs attributes by name, so a renamed attribute looks like one removed and one added: migration succeeds and the values are dropped. Setting the new attribute's renaming identifier to its old name makes Core Data copy them across.

open as a page

When you build a Core Data NSManagedObjectModel in code, what must each entity and attribute set, and why should the process create the model only once?

level: middleimportance: should knowfreq 32%

basics

~20 s

Each NSEntityDescription needs a name, a managedObjectClassName and properties; each NSAttributeDescription needs a name, a real type, optionality and defaults. Build one shared model: a second one claiming the same subclass leaves Plant(context:) unable to pick its entity.

open as a page

In Core Data, what changes when you mark Course.lessons as an ordered to-many relationship, and when is a position attribute the better choice?

level: middleimportance: should knowfreq 38%

basics

~20 s

An ordered to-many relationship makes Core Data persist the members' order: the property becomes an NSOrderedSet and codegen adds indexed accessors. Use an integer position attribute instead when fetch requests must sort or filter by that order.

open as a page

In Core Data, how do you move an app's SQLite store into an app group so its widget extension can open the same file?

level: middleimportance: should knowfreq 40%

basics

~20 s

Give the app and widget the same App Group, open the store at a URL inside its container, and move existing users' store there once with the coordinator's replacePersistentStore and destroyPersistentStore, never a FileManager copy of the .sqlite file alone.

open as a page

In Core Data, after an NSBatchDeleteRequest removes old expenses, why does the dashboard still show them, and how do you make viewContext see the change?

level: seniorimportance: should knowfreq 45%

basics

~20 s

Batch requests change rows in the store without loading objects or saving a context, so viewContext gets nothing to merge. Set resultType to return object IDs and pass them to NSManagedObjectContext.mergeChanges(fromRemoteContextSave:into:), or consume persistent history.

open as a page

In Core Data, why does a viewContext save fail with error 133020 after a background import changed the same Expense, and which merge policy fits?

level: seniorimportance: should knowfreq 50%

basics

~10 s

133020 is NSManagedObjectMergeError: viewContext edited an Expense whose stored row changed after it was loaded, and the default NSErrorMergePolicy refuses such saves. Setting NSMergePolicy.mergeByPropertyObjectTrump keeps the user's edited properties and the import's other changes.

open as a page

In Core Data, how do you build a statistics screen showing sightings and total birds per region without fetching every Sighting object?

level: seniorimportance: should knowfreq 40%

basics

~20 s

Use a dictionary-result fetch: propertiesToFetch lists region plus NSExpressionDescription columns for count: and sum:, propertiesToGroupBy groups by region, and the store returns one small dictionary per region. Those results reflect saved data only, never the context's unsaved changes.

open as a page

In Core Data, which model changes can lightweight migration infer, which make it fail at launch, and which does it accept while silently losing data?

level: seniorimportance: should knowfreq 40%

basics

~20 s

Lightweight migration infers added, removed and renamed entities, attributes and relationships, plus optionality changes with a default. A String-to-number change or a mandatory attribute with nil rows fails the load; moving a string into a new entity is inferred and loses the data.

open as a page

In Core Data on iOS 17 or later, why can one NSCustomMigrationStage not move Album's artist string into a new Artist entity, and how do staged stages fix it?

level: seniorimportance: should knowfreq 35%

basics

~20 s

A custom stage's willMigrateHandler runs before the schema changes, when Artist does not exist, and its didMigrateHandler runs after, when artistName is gone. Add an intermediate version holding both, fill Artist in that stage's didMigrateHandler, then drop the string in a second stage.

open as a page

A Core Data model logs that a Transformable attribute is using nil or an insecure NSValueTransformer; what does that mean, and how do you store a custom watering schedule safely?

level: seniorimportance: should knowfreq 42%

basics

~10 s

A Transformable attribute with no transformer, or a deprecated keyed-unarchive one, unarchives whatever classes the data names. Name NSSecureUnarchiveFromData for Foundation values, or register an NSSecureUnarchiveFromDataTransformer subclass listing your NSSecureCoding class in allowedTopLevelClasses.

open as a page

A Core Data Plant entity has a uniqueness constraint on speciesName, and saving a second plant of the same species fails with error 133021; why, and what fixes it?

level: seniorimportance: should knowfreq 48%

basics

~10 s

Uniqueness constraints are enforced at save, and the default NSErrorMergePolicy refuses any conflict with NSManagedObjectConstraintMergeError (133021). Setting the context's mergePolicy to NSMergePolicy.mergeByPropertyObjectTrump turns the duplicate insert into an update of the existing row.

open as a page

In Core Data, why does memory keep climbing while an export walks all 600 students and their courses, and how does refresh(_:mergeChanges:) bring it down?

level: seniorimportance: should knowfreq 42%

basics

~20 s

Every fault the export fires stays filled, and filled objects hold strong references to the related objects they reached, so the graph grows. refresh(_:mergeChanges: false) turns an object back into a fault and breaks those references, letting the graph be released.

open as a page

Your Core Data app shares its store with a widget; why does the app's list miss changes the widget saved, and how do you fix it?

level: seniorimportance: should knowfreq 40%

basics

~20 s

The widget saves through its own coordinator in another process, so no save notification reaches the app's contexts. Turn on persistent history and remote change notifications in both processes, then on each remote change fetch history after your saved token and merge it.

open as a page

As the lead on a Core Data expense app, what context rule would you set for which contexts write, which read, and how changes reach the UI?

level: principalimportance: should knowfreq 35%

basics

~20 s

A common rule: viewContext serves reads and small edits, one kept background context does imports, every write path ends in a merge viewContext receives, each context gets a merge policy, and debug builds run the concurrency argument.

open as a page

showing 1–30 of 33