Swift 3 Core Data Delete Object
The result of a fetch is an array of managed objects, in your case[Event]
, so you can enumerate the array and delete all matching objects.
Example (using try?
instead of try!
to avoid a crash in the case
of a fetch error):
if let result = try? context.fetch(fetchRequest) {
for object in result {
context.delete(object)
}
}
do {
try context.save()
} catch {
//Handle error
}
If no matching objects exist then the fetch succeeds, but the resulting
array is empty.
Note: In your code, object
has the type [Event]
and therefore in
context.delete(object)
the compiler creates a call to the
public func delete(_ sender: AnyObject?)
method of NSObject
instead of the expected
public func delete(_ object: NSManagedObject)
method of NSManagedObjectContext
. That is why your code compiles
but fails at runtime.
Deleting all data in a Core Data entity in Swift 3
You're thinking of NSBatchDeleteRequest
, which was added in iOS 9. Create one like this:
let fetch = NSFetchRequest<NSFetchRequestResult>(entityName: "Employee")
let request = NSBatchDeleteRequest(fetchRequest: fetch)
You can also add a predicate if you only wanted to delete instances that match the predicate. To run the request:
let result = try managedObjectContext.executeRequest(request)
Note that batch requests don't update any of your current app state. If you have managed objects in memory that would be affected by the delete, you need to stop using them immediately.
Core Data with SWIFT: How to delete object from Relationship entity?
Using predicates is exactly right. You'd want to set the predicate for the fetchRequest
let predicate = NSPredicate(format: "uniqueKey == %@", "value")
fetchRequest.predicate = predicate
Then you can delete the result
Related Topics
Get an Array of Property Values from an Object Array
Automaticallyadjustsscrollviewinsets Not Working
Nsuserdefaults Not Cleared After App Uninstall on Simulator
Xcode 7 UI Testing: How to Dismiss a Series of System Alerts in Code
Getting a Device Udid from .Mobileconfig
Uitableview with Multiple Sections Using Realm and Swift
How to Set Adaptive Multiline Uilabel Text
iOS 7/Xcode 5: Access Device Launch Images Programmatically
How to Embed Youtube Video on iOS and Play It Directly on Uiwebview Without Full Screen
Posting Video on Instagram Using Hooks
Core Audio Offline Rendering Genericoutput
Nsindexpath.Item VS Nsindexpath.Row
Levenshtein Distance Algorithm Better Than O(N*M)