insertNewObjectForEntityForName always creates a new managed object. To update an existing record, first fetch it with a predicate, modify the fetched object’s properties, then call save() on the context.Why this happens
When you call NSEntityDescription.insertNewObjectForEntityForName(_:in:) (or the modern Entity(context:) initializer), Core Data always creates a brand-new managed object and inserts it into the context. If you run that code a second time for the same logical entity—say, a user’s login token—you end up with two LoginData rows in the store. The fetch request in loadLoginData() returns the first one it finds, so the token never appears to change.
The fix is straightforward: fetch first, then decide whether to insert or update. Core Data has no built-in “upsert” command; you must write the logic yourself.
How to fix it
1. Fetch the existing object, update if found, insert only if missing (recommended)
This pattern works on every iOS version and makes the intent explicit. Use a typed NSFetchRequest and a predicate that uniquely identifies the record you want.
func saveLoginData(accessToken: String, userName: String) {
let context = persistentContainer.viewContext
// 1. Build a fetch request for the exact record
let request: NSFetchRequest<LoginData> = LoginData.fetchRequest()
request.predicate = NSPredicate(format: "userName == %@", userName)
request.fetchLimit = 1
// 2. Try to fetch an existing object
if let existing = try? context.fetch(request).first {
// 3. Update the existing managed object
existing.accessToken = accessToken
} else {
// 4. No match → insert a new one
let newLogin = LoginData(context: context)
newLogin.userName = userName
newLogin.accessToken = accessToken
}
// 5. Persist the change
try? context.save()
}
Key points
– LoginData is an NSManagedObject subclass generated from the model (Editor ▸ Create NSManagedObject Subclass). Using the subclass gives you compile-time property access (existing.accessToken) instead of stringly-typed setValue(_:forKey:).
– fetchLimit = 1 stops the fetch as soon as one match is found.
– Wrap the fetch and save in do/catch if you need to surface errors to the UI.
2. Lightweight “upsert” helper for reusable code
If you perform this pattern in many places, extract a small generic helper:
extension NSManagedObjectContext {
func fetchOrCreate<T: NSManagedObject>(matching predicate: NSPredicate, configure: (T) -> Void) throws -> T {
let request = T.fetchRequest()
request.predicate = predicate
request.fetchLimit = 1
if let existing = try fetch(request).first as? T {
configure(existing)
return existing
} else {
let new = T(context: self)
configure(new)
return new
}
}
}
// Usage
try context.fetchOrCreate(matching: NSPredicate(format: "userName == %@", userName)) { (login: LoginData) in
login.accessToken = accessToken
}
try context.save()
This keeps view-controller code clean and centralizes the fetch-or-create logic.
3. Batch update for large datasets (advanced)
If you need to update many rows at once (e.g., marking all messages as read), use NSBatchUpdateRequest. It runs at the SQLite level without loading objects into memory.
let batch = NSBatchUpdateRequest(entityName: "Message")
batch.predicate = NSPredicate(format: "isRead == NO")
batch.propertiesToUpdate = ["isRead": true]
batch.resultType = .updatedObjectIDsResultType
let result = try context.execute(batch) as? NSBatchUpdateResult
if let objectIDs = result?.result as? [NSManagedObjectID] {
// Merge changes into the context so fetched results controllers stay in sync
let changes = [NSUpdatedObjectsKey: objectIDs]
NSManagedObjectContext.mergeChanges(fromRemoteContextSave: changes, into: [context])
}
Do not use batch updates for single-record changes—the overhead isn’t worth it.
How to prevent it
- Generate
NSManagedObjectsubclasses for every entity (Editor ▸ Create NSManagedObject Subclass). Typed properties eliminatesetValue(_:forKey:)typos. - Add a unique constraint in the data model inspector (e.g.,
userNameunique). Core Data will then throwNSConstraintConflictErroron duplicate inserts, forcing you to handle the conflict explicitly. - Adopt the fetch-or-create pattern everywhere you write data. A shared helper (see Fix #2) makes this the path of least resistance.
- Unit-test the upsert logic with an in-memory store (
NSInMemoryStoreType) so duplicates are caught in CI.
FAQ
Why does my fetch request return the old value even after I call save()?
The fetch request in loadLoginData() likely runs against the same context that already has the stale object registered. After save(), call context.refreshAllObjects() or re-fetch with a new context (e.g., a background context) to see the committed values.
Can I use NSBatchUpdateRequest for a single record?
Technically yes, but it bypasses the context’s object graph, so any fetched results controllers, SwiftUI @FetchRequest, or in-memory changes won’t know about the update. Stick with the fetch-then-update approach for single records.
What if two threads try to upsert the same user at the same time?
With a unique constraint on userName, the second save() will throw NSConstraintConflictError. Catch it, re-fetch the existing object in the same context, apply the new values, and retry the save. This is the standard “optimistic locking” pattern Core Data expects.
Parts of this guide are adapted from content licensed under CC BY-SA 3.0; this article is shared under the same license.