Why this happens
When you call context.fetch(fetchRequest), Core Data returns an array of managed objects ([Profile] in the example) — even if only one object matches the predicate. The code in the question passes this array directly to context.delete(_:).
NSManagedObjectContext has a delete(_ object: NSManagedObject) method, but because the array is typed as [Profile], the compiler falls back to NSObject‘s delete(_ sender: AnyObject?) method (inherited from Objective-C). This compiles without error but does nothing useful at runtime, so the object remains in the store.
The fix is two-fold: iterate the fetched array to delete each object individually, then call save() on the context to commit the change to the persistent store.
How to fix it
1. Fetch, iterate, delete, then save (recommended)
Use optional binding with try? to avoid a crash if the fetch itself throws, then loop over the results and delete each one. Finally, wrap context.save() in a do-catch block to handle any persistence errors.
func deleteProfile(withID id: Int) {
let fetchRequest: NSFetchRequest<Profile> = Profile.fetchRequest()
fetchRequest.predicate = NSPredicate(format: "profileID == %d", id)
guard let objects = try? context.fetch(fetchRequest) else {
print("Fetch failed")
return
}
for object in objects {
context.delete(object)
}
do {
try context.save()
} catch {
print("Failed to save after delete: \(error)")
// Handle error — e.g., rollback, show alert, log to analytics
}
}
Key points:
– NSPredicate with %d placeholder is safer than string interpolation.
– try? returns nil on fetch error instead of crashing.
– The for loop ensures each NSManagedObject is passed to the correct delete(_:) overload.
– context.save() persists the deletion; without it, the change exists only in memory.
2. Batch delete for large datasets (iOS 9+ / macOS 10.11+)
If you need to delete many objects at once, use NSBatchDeleteRequest to avoid loading every object into memory. This runs directly on the persistent store.
func deleteProfilesBatch(withID id: Int) {
let fetchRequest: NSFetchRequest<NSFetchRequestResult> = Profile.fetchRequest()
fetchRequest.predicate = NSPredicate(format: "profileID == %d", id)
let batchDelete = NSBatchDeleteRequest(fetchRequest: fetchRequest)
batchDelete.resultType = .resultTypeObjectIDs // optional: get deleted object IDs
do {
let result = try context.execute(batchDelete) as? NSBatchDeleteResult
// If you need to merge changes into the context:
if let objectIDs = result?.result as? [NSManagedObjectID] {
let changes = [NSDeletedObjectsKey: objectIDs]
NSManagedObjectContext.mergeChanges(fromRemoteContextSave: changes, into: [context])
}
} catch {
print("Batch delete failed: \(error)")
}
}
Batch deletes are faster for large numbers of objects but bypass the context’s normal change tracking, so you must merge the result back if the context needs to stay in sync.
How to prevent it
- Always remember that
fetch(_:)returns an array, even for single-result predicates. - Prefer
try?ordo-catchovertry!for fetch requests to avoid crashes on store errors. - Call
context.save()after any mutation (insert, update, delete) that must persist. - Use
NSPredicateformat specifiers (%@,%d,%f) instead of string interpolation to avoid injection issues and formatting bugs. - For bulk operations, consider
NSBatchDeleteRequestto keep memory usage low.
FAQ
Why does my code compile but not delete the object?
The fetched result is an array ([Profile]). Passing an array to context.delete(_:) matches NSObject.delete(_ sender: AnyObject?), which does nothing for managed objects. The correct NSManagedObjectContext.delete(_ object: NSManagedObject) is never called.
Do I have to call save() after every delete?
Yes. Deleting an object marks it for deletion in the context, but the change is only written to the persistent store when you call save(). Until then, the object will still appear in subsequent fetches.
Can I delete an object without fetching it first?
If you already have a reference to the NSManagedObject (e.g., passed from another view), you can call context.delete(object) directly — no fetch needed. Fetching is only required when you need to locate the object by a property like profileID.
Parts of this guide are adapted from content licensed under CC BY-SA 4.0; this article is shared under the same license.