Why this happens
Core Data doesn’t expose a direct “update” method because it treats managed objects as in-memory representations of persistent store records. When you fetch an object, you’re working with a managed object that’s already registered in the context. Modifying its properties marks the object as “dirty,” and calling save() on the context writes those changes to the persistent store.
The key insight: fetch → modify → save is the complete update cycle. There’s no separate update API because the context tracks changes automatically once the object is in memory.
How to fix it
1. Fetch the object with a predicate (most common approach)
Use NSFetchRequest with an NSPredicate to locate the specific object you want to update, then modify its properties and save.
import CoreData
func updateFavorite(title: String, newTitle: String, context: NSManagedObjectContext) throws {
let request = NSFetchRequest<Favorite>(entityName: "Favorite")
request.predicate = NSPredicate(format: "title == %@", title)
request.fetchLimit = 1
let results = try context.fetch(request)
guard let favorite = results.first else {
throw NSError(domain: "CoreDataUpdate", code: 404, userInfo: [
NSLocalizedDescriptionKey: "Favorite with title '" + title + "' not found"
])
}
favorite.title = newTitle
if context.hasChanges {
try context.save()
}
}
Key points:
– Set fetchLimit = 1 when you only need one match
– Always check context.hasChanges before saving to avoid unnecessary I/O
– Wrap in do/catch or propagate throws for proper error handling
2. Update using objectID (when you already have a reference)
If you already hold the NSManagedObjectID (passed between threads, stored in UserDefaults, etc.), fetch directly by ID—no predicate needed.
func updateFavoriteByID(_ objectID: NSManagedObjectID, newTitle: String, context: NSManagedObjectContext) throws {
let favorite = try context.existingObject(with: objectID) as! Favorite
favorite.title = newTitle
if context.hasChanges {
try context.save()
}
}
existingObject(with:) throws if the object was deleted or doesn’t exist, which is safer than object(with:) that returns a fault.
3. Batch update for multiple objects (iOS 13+ / macOS 10.15+)
When updating many objects with the same change, use NSBatchUpdateRequest to avoid loading objects into memory.
func markAllFavoritesAsRead(context: NSManagedObjectContext) throws {
let request = NSBatchUpdateRequest(entityName: "Favorite")
request.propertiesToUpdate = ["isRead": true]
request.resultType = .updatedObjectIDsResultType
let result = try context.execute(request) as? NSBatchUpdateResult
if let objectIDs = result?.result as? [NSManagedObjectID] {
// Merge changes into context so fetched results controllers update
let changes = [NSUpdatedObjectsKey: objectIDs]
NSManagedObjectContext.mergeChanges(fromRemoteContextSave: changes, into: [context])
}
}
Batch updates bypass the context’s change tracking, so you must manually merge the objectIDs back into any affected contexts.
4. Swift Concurrency / async context (iOS 15+ / macOS 12+)
Use perform on the context for thread-safe updates from async code.
func updateFavoriteAsync(title: String, newTitle: String) async throws {
let container = persistentContainer // your NSPersistentContainer
try await container.performBackgroundTask { context in
let request = NSFetchRequest<Favorite>(entityName: "Favorite")
request.predicate = NSPredicate(format: "title == %@", title)
request.fetchLimit = 1
guard let favorite = try context.fetch(request).first else {
throw UpdateError.notFound
}
favorite.title = newTitle
if context.hasChanges {
try context.save()
}
}
}
enum UpdateError: Error {
case notFound
}
performBackgroundTask creates a private queue context, performs the work, and saves automatically if no error is thrown.
How to prevent it
- Always save after modifications — unsaved changes exist only in memory and are lost on app termination
- Use fetch limits —
fetchLimit = 1for single-object updates avoids loading unnecessary rows - Prefer objectID for cross-thread references — managed objects are not thread-safe; pass
objectIDinstead - Merge batch updates — call
mergeChanges(fromRemoteContextSave:into:)afterNSBatchUpdateRequestso UI stays in sync - Validate before saving — implement
validateForUpdate()in yourNSManagedObjectsubclass for custom validation rules
FAQ
Can I update a Core Data object without fetching it first?
No. You must fetch the object (or have its objectID) to get a managed object reference in the context. Core Data doesn’t support SQL-style UPDATE ... WHERE directly on the store without loading objects, except via NSBatchUpdateRequest which still requires an entity and predicate.
Why don’t my UI updates appear after a batch update?
NSBatchUpdateRequest modifies the persistent store directly and bypasses the managed object context’s change tracking. You must merge the returned objectIDs into your view context using mergeChanges(fromRemoteContextSave:into:) so fetched results controllers and SwiftUI @FetchRequest properties refresh.
Is it better to update on the main context or a background context?
For single-object updates triggered by UI, the main context (viewContext) is fine. For bulk updates, imports, or any work that might block, use a background context (performBackgroundTask or newBackgroundContext()) to keep the main thread responsive.
Parts of this guide are adapted from content licensed under CC BY-SA 3.0; this article is shared under the same license.