skip to content

Fetch Requests & Predicates

NSFetchRequest with predicates, sort descriptors, limits and result types, plus NSFetchedResultsController feeding a list. Interviewers probe predicate syntax and fetching only what a screen needs.

on this pageshow

explore

questions

5

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, 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, 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, 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, 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