In Core Data, how do you build an NSFetchRequest for one region's bird sightings, newest first, and what does executing it return?
answer
- entity, predicate, sort descriptors
- the request's generic result type
- sort descriptor array order matters
- fetch(_:) throws, returns a typed array
- unsaved inserts can match too
basics
~20 sCreate 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 sA 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 linesimport 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
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.
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.
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.
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.