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.
Swift 3: How to delete the single record in the Core Data when a UIbutton is Pressed
let fetchRequest = NSFetchRequest<NSFetchRequestResult>(entityName: "FavProfile")
let predicate = NSPredicate(format: "profileID == %@", id as CVarArg)
fetchRequest.predicate = predicate
let moc = getContext()
let result = try? moc.fetch(fetchRequest)
let resultData = result as! [FavProfile]
for object in resultData {
moc.delete(object)
}
do {
try moc.save()
print("saved!")
} catch let error as NSError {
print("Could not save \(error), \(error.userInfo)")
}
use predicate for profileID.
Related Topics
How to Use Device Instead of Simulator
Differences Between Websockets and Long Polling for Turn Based Game Server
How to Change Height of Grouped Uitableview Header
Using iOS Gamekit's "Bluetooth Bonjour" with Other Platforms
Present Uialertcontroller on Top of Everything Regardless of the View Hierarchy
iOS - Uiimagewritetosavedphotosalbum
Uitableview Add Cell Animation
How to Link Googleanalytics 3.01 with Xcode 5 (Missing Required Architecture X86_64)
Should I Be Using Awakefromnib or Initwithcoder Here
Present a View Controller, Dismiss It and Present a Different One in Swift
How to Upload Audio with Alamofire Multipart Upload
How to Draw a Smooth Circle with Cashapelayer and Uibezierpath
What Happens If My Distribution Certificate Expires
Uiimagepickercontroller Camera View Rotating Strangely on iOS 8 (Pictures)