5

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.

Kara
  • 6,115
  • 16
  • 50
  • 57
Kapil Choubisa
  • 5,152
  • 9
  • 65
  • 100
  • It would be helpful if you showed the entire error instead of just a small snippet. – Marcus S. Zarra Apr 26 '16 at 00:10
  • 1
    This is all what I get as an error. – Kapil Choubisa Apr 26 '16 at 11:15
  • The console must be outputting more than that. I have never seen any error in Xcode put out just one line. I would suggest casting your error to an `NSError` and printing out its `userInfo` and seeing if there are underlying errors. – Marcus S. Zarra Apr 26 '16 at 16:09
  • 3
    Nope, he's right. That is the entire error. I'm seeing the same thing when doing a simple fetch. No idea what's going on. – Aron Jun 28 '16 at 04:24
  • @MarcusS.Zarra I am also getting the same error. Its `userInfo` dictionary is empty. Don't know what's wrong here. – Harshil Apr 25 '17 at 09:32
  • Bit of a zombie resurrection :) What is the full output of the error? Maybe open a new question? Also look at Christopher's answer below. – Marcus S. Zarra Apr 25 '17 at 19:44
  • Related: [What is Foundation._GenericObjCError.NilError?](https://stackoverflow.com/q/55640917/3939277) – Ky - Apr 11 '19 at 20:48

1 Answers1

4

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.

Christopher Rogers
  • 6,759
  • 1
  • 22
  • 13