Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Foundation._GenericObjCError.NilError from core data batch delete

I am trying to use batch delete feature of core data. I have an entity named Car. That entity has a column name modelNumber as Int. I want to delete all cars which has modelNumber older than 2000. Here is my code:

func deleteCarsOlderThan(modelNumber: Int) {
    let predicate = NSPredicate(format: "modelNumber <= %@", NSNumber(int: modelNumber))

    let fetchRequest = NSFetchRequest(entityName: "Car")
    fetchRequest.predicate = predicate

    let deleteRequest = NSBatchDeleteRequest(fetchRequest: fetchRequest)
    deleteRequest.resultType = .ResultTypeCount
    do {
        let result = try self.fhirManagedObjectContext.executeRequest(deleteRequest)
        try self.fhirManagedObjectContext.save()
    }
    catch {
        print(error)
    }
}

While executing this code, control goes to catch block and it gives an error says: Foundation._GenericObjCError.NilError. My fetch request is working well as if I use:

    let olderCars = self.executeFetchRequest(fetchRequest)

it returns me an array of older cars. I don't know where I am doing wrong. I am using iOS9 for this purpose.

like image 653
Kapil Choubisa Avatar asked Oct 19 '22 10:10

Kapil Choubisa


People also ask

How do I delete all data from core data?

Delete Everything (Delete All Objects, Reset Core Data) One approach to delete everything and reset Core Data is to destroy the persistent store. Deleting and re-creating the persistent store will delete all objects in Core Data.

How to delete from Core Data Swift?

Table views have a built-in swipe to delete mechanic that we can draw upon to let users delete commits in our app. Helpfully, managed object context has a matching delete() method that will delete any object regardless of its type or location in the object graph.


1 Answers

TL;DR: While self.fhirManagedObjectContext is non-optional, it's probably returning nil from Objective-C.

The error you observed is generated by Swift's Foundation bridging runtime. (See the source code here.) This occurs when an Objective-C method with an error pointer returns a failure value (NO or nil), but no actual error was passed back via the NSError pointer. This could either be the result of a bug in Core Data or, more likely, a nil managed object context that when using Objective-C method dispatch causes the method to appear to return NO.

like image 118
Christopher Rogers Avatar answered Oct 21 '22 04:10

Christopher Rogers