Core Data — faulting, FRC, batch requests & persistent history

ios-platform · folio

In one line: Fetched objects are faults, filled on first touch from the row cache or a SQL SELECT — performance = few round-trips. Batch requests run as SQL on the store: fast, but no context sees them until you merge the returned IDs. Persistent history logs every transaction (who, what) in the store, so each context, process and extension catches up from its own token.

Download PDF Print view LaTeX source

Core Data — faulting, FRC, batch requests & persistent history — figure 1

Fetch knobs

Knob (default)Effect · use
returnsObjectsAsFaults (true)false: filled now; relationships still faults
includesPropertyValues (true)false: IDs only, no row cache — deletes
fetchBatchSize (0 = all)IDs first, rows in pages — long lists, FRC
relationshipKeyPaths
ForPrefetching
one query per key path, not a fault per object: kills N+1
propertiesToFetch +
.dictionaryResultType
read-only dicts, no objects; + NSExpressionDescription = SUM/AVG in SQL
count(for:) · fetchLimitSELECT COUNT · LIMIT

A fetch always runs SQL; its faults then fire from the row cache it filled. Big import: save + reset() every N rows.

Batch requests — SQL on the store (SQLite only)

RequestiOSNotes · result type for IDs
NSBatchUpdate
Request
8propertiesToUpdate = one UPDATE
.updatedObjectIDsResultType
NSBatchDelete
Request
9basic delete rules; Deny unsupported
.resultTypeObjectIDs
NSBatchInsert
Request
13dicts or a handler; unique constraints checked; no relationships(unverified) · .objectIDs

All skip the context: no validation, no willSave, no notifications; objects in memory go stale. Merge the IDs: class method mergeChanges(fromRemoteContextSave:into:) — or let history do it.

Example — FRC + diffable, and a batch delete the UI sees

let r = NSFetchRequest<Item>(entityName: "Item")
r.sortDescriptors = [NSSortDescriptor(key: "date", ascending: false)]
r.fetchBatchSize = 30
frc = NSFetchedResultsController(fetchRequest: r, managedObjectContext:
        viewContext, sectionNameKeyPath: nil, cacheName: nil)
frc.delegate = self; try frc.performFetch()
func controller(_ c: NSFetchedResultsController<NSFetchRequestResult>,
    didChangeContentWith s: NSDiffableDataSourceSnapshotReference) {
  dataSource.apply(s as NSDiffableDataSourceSnapshot<String, NSManagedObjectID>)
}
// inside bg.perform: 50k rows gone in one DELETE, then tell viewContext
let del = NSBatchDeleteRequest(fetchRequest: NSFetchRequest(entityName: "Item"))
del.resultType = .resultTypeObjectIDs
let res = try bg.execute(del) as? NSBatchDeleteResult
let ids = res?.result as? [NSManagedObjectID] ?? []
NSManagedObjectContext.mergeChanges(fromRemoteContextSave:
    [NSDeletedObjectsKey: ids], into: [viewContext])   // FRC animates it

NSFetchedResultsController

  • Watches one context for one fetch request (≥ 1 sort descriptor; sectionNameKeyPath follows the first sort key). It moves only when a change lands in that context — a save there or a merge.
  • iOS 13 controller(_:didChangeContentWith:): a snapshot of NSManagedObjectIDs (sections = String); implement it and the per-row callbacks stop. A CollectionDifference variant exists too.
  • An in-place edit keeps the same ID, so the diff sees nothing: reconfigureItems (iOS 15) the updated IDs, or let cells observe their object.

Persistent history

  • Each NSPersistentHistoryTransaction: token, timestamp, author, contextName, changes (object ID, insert/update/delete, updatedProperties). Name writers: ctx.transactionAuthor = "importer".
  • Read on a background context with NSPersistentHistoryChangeRequest.fetchHistory(after:); persist the last token (NSSecureCoding) per reader.
  • Purge with deleteHistory(before:) a token, date or transaction. Once tracked, opening the store without the key makes it read-only.

App + extension on one store

Store URL in the App Group container; both targets set both keys on the store description before loadPersistentStores. Each process has its own coordinator, so automaticallyMergesChangesFromParent never sees the other — each reader keeps its own token in the group and merges foreign authors.

Debug — launch arguments

-com.apple.CoreData.SQLDebug 1 (up to 4): every SQL statement + time — N+1 shows as a SELECT per row. …ConcurrencyDebug 1: crash on wrong-queue access. …MigrationDebug 1: migration steps.

Traps

  • FRC stale after an import: the change never reached its context (no merge, a batch request, another process).
  • Batch delete, UI still shows the rows — nobody merged the IDs.
  • Purging on a timer before the widget read it: it silently misses changes.
  • Reading objectID or isFault does not fire a fault.

Remember

Faults are free until touched; batches are fast until forgotten; history is read after your token and purged behind the slowest reader.

Report a problem ·Discuss this folio