skip to content

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%

answer

  1. let the store do the arithmetic
  2. dictionaryResultType and propertiesToFetch
  3. NSExpressionDescription names each column
  4. propertiesToGroupBy, like SQL GROUP BY
  5. unsaved changes are left out

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.

solid answer

~40 s

I set `resultType = .dictionaryResultType` and list in `propertiesToFetch` the `region` attribute plus two `NSExpressionDescription`s: one named `sightings` wrapping `NSExpression(forFunction: "count:", arguments:)`, one named `birds` wrapping `sum:` over `birdCount`, each with a result type such as `.integer64`. `propertiesToGroupBy = ["region"]` makes the aggregates run per region, and the store returns one dictionary per group keyed by those names, so no `Sighting` objects are created. Every fetched value must be a grouped column, an aggregate or a literal, and `havingPredicate` filters the groups afterwards. Two traps: dictionary results read the persistent store as it stands, ignoring the context's unsaved inserts, edits and deletes; and they are plain values that never update themselves, so the screen refetches after a save. For the list of families present, `returnsDistinctResults` with one property is enough.

code

swift · 20 lines
swift
import CoreData

func sightingsPerRegion(context: NSManagedObjectContext) throws -> [[String: Any]] {
    let total = NSExpressionDescription()
    total.name = "sightings"
    total.expression = NSExpression(forFunction: "count:", arguments: [NSExpression(forKeyPath: "species")])
    total.resultType = .integer64

    let birds = NSExpressionDescription()
    birds.name = "birds"
    birds.expression = NSExpression(forFunction: "sum:", arguments: [NSExpression(forKeyPath: "birdCount")])
    birds.resultType = .integer64

    let request = NSFetchRequest<NSDictionary>(entityName: "Sighting")
    request.resultType = .dictionaryResultType
    request.propertiesToFetch = ["region", total, birds]
    request.propertiesToGroupBy = ["region"]
    request.sortDescriptors = [NSSortDescriptor(key: "region", ascending: true)]
    return try context.fetch(request) as? [[String: Any]] ?? []
}

go deeper

for a junior

Recall that a fetch can return dictionaries instead of objects, and that propertiesToFetch decides which keys each dictionary holds.

for a middle

Explain the parts: NSExpressionDescription with a name, an expression and a result type, propertiesToGroupBy for per-group aggregates, and havingPredicate for filtering groups.

for a senior

Show the production judgment: aggregates ignore unsaved changes, results never refresh on their own, and the sorted fetch with a limit of 1 when pending changes must count.

for a principal

Decide where statistics are computed: store-side aggregates refetched after saves, or maintained counters on a parent entity when screens read totals far more often than data changes.

## Why not fetch and loop A statistics screen for the bird-watching log shows, per region, how many sightings were logged and how many birds they counted. Fetching all 30,000 `Sighting` objects and summing in Swift creates 30,000 managed objects, loads every row's data, and keeps them registered with the context, all to produce three rows of numbers. A **dictionary-result fetch** asks the store to do the grouping and arithmetic and returns only the answer. ## Dictionary results - Set **`resultType = .dictionaryResultType`** on an `NSFetchRequest<NSDictionary>`. - **`propertiesToFetch`** lists what each dictionary contains: attribute names as strings or `NSPropertyDescription`s, to-one relationships, and **`NSExpressionDescription`**s for computed columns. - Each dictionary's keys are the property names, or the `name` you gave each expression description. - No managed objects are created and nothing is registered with the context. - **`returnsDistinctResults = true`** returns each distinct combination of the fetched properties once, which suits "which families appear in the log". It is used only for dictionary results. ## Building the aggregate request 1. Create an `NSExpressionDescription`, set its `name` (the dictionary key), its `expression`, such as `NSExpression(forFunction: "count:", arguments: [NSExpression(forKeyPath: "species")])`, and its result type: `resultType = .integer64` in the Swift overlay since iOS 15, or `expressionResultType` with an `NSAttributeType`. 2. Repeat for `sum:` over `birdCount`; Foundation's `NSExpression` also offers functions such as `average:`, `min:` and `max:`. 3. Set `propertiesToFetch = ["region", total, birds]`. 4. Set `propertiesToGroupBy = ["region"]`, so the aggregates are computed per region instead of over the whole table. 5. Sort by `region` if the screen needs a stable order, then `try context.fetch(request)`. Apple's documentation is explicit that an expression description belongs in the fetch request's `propertiesToFetch` and must not be added to an entity's properties. ## Rules the store enforces | Setting | Rule | |---|---| | `propertiesToGroupBy` | requires `.dictionaryResultType`; key paths cannot contain to-many steps | | `propertiesToFetch` with grouping | every value must be a literal, an aggregate or a grouped column | | `havingPredicate` | filters the groups after grouping; requires `propertiesToGroupBy` | | `NSExpressionDescription` | allowed in `propertiesToFetch` for dictionary results, not with managed-object results | ## Freshness and pending changes - **Unsaved changes are ignored.** Apple's documentation says `includesPendingChanges = true` is not supported with dictionary results, aggregates included: the array reflects the persistent store and takes no account of the context's pending inserts, updates or deletes. A sighting logged but not yet saved does not appear in the totals. - For a simple `max` or `min` that must include pending changes, the documented workaround is an ordinary object fetch sorted on that attribute with `fetchLimit = 1`. - **Results are snapshots.** The dictionaries are plain values, so nothing updates them when sightings change; refetch when the context saves. How a screen learns that a background save happened is covered with managed object contexts. ## Reading the results The fetch returns `[NSDictionary]`, which bridges to `[[String: Any]]`. For the request above, each element looks like `["region": "North", "sightings": 1000, "birds": 3000]`: - grouped attributes come back as their stored values, here a `String`; - aggregate columns come back as `NSNumber`, so read them with `as? Int` or `as? Int64`; - the keys are exactly the attribute names and the `name` you gave each expression description, so read them back with those same strings; - with `returnsDistinctResults` and a single property such as `family`, each dictionary holds one key and the array lists each family once. Map the dictionaries into a small value type for the screen right after the fetch, so the rest of the code never handles untyped keys. ## When you do need the objects If code really must walk every object, for example to compute something the store cannot, set `returnsObjectsAsFaults = false`; the documentation notes this avoids the extra cost of firing each fault when every property will be read. The grouping and aggregate functions here run inside the store; how SQLite itself plans and executes them is a database topic of its own.

  • The statistics screen should list only regions with more than 100 sightings; where does that condition go?
    In `havingPredicate`, which filters rows after the grouping, the way `HAVING` follows `GROUP BY` in SQL. The fetch request's ordinary `predicate` filters individual sightings before they are grouped, so it cannot test a per-region count. A `havingPredicate` requires `propertiesToGroupBy` to be set.
  • The newest sighting date per region must include an entry the user has not saved yet; what do you use?
    Not a dictionary `max:` aggregate, because dictionary results ignore pending changes. Apple's documented alternative is an ordinary object fetch for that region, sorted on `seenAt` descending with `fetchLimit = 1`; object fetches include unsaved inserts and edits by default.
  • Why does the totals screen still show yesterday's numbers after the user logs a sighting and saves?
    The dictionaries are values captured when the fetch ran; nothing tracks them, unlike managed objects or a fetched results controller. Run the aggregate fetch again when the context saves, then redraw the screen.

  • Dictionary results include the context's unsaved inserts, like object fetches do.
  • propertiesToGroupBy works with the default managed-object result type.
  • An NSExpressionDescription can be added to the entity's properties for reuse.
  • Fetching every object and summing in Swift costs about the same as an aggregate.
  • Fetched dictionaries update themselves when the underlying sightings change.