2

I am trying to delete an object in my database by his objectID. I know is objectID (choosenID), which is created by xcode.

I have done this:

let app = UIApplication.shared.delegate as! AppDelegate
let context = app.persistentContainer.viewContext
let request = NSFetchRequest<NSFetchRequestResult>(entityName: "Notes")
request.predicate = NSPredicate(format: "objectID = %@", "\(choosenID)")
request.returnsObjectsAsFaults = false

    do {
        let results = try context.fetch(request)

        if results.count > 0 {

            for result in results as! [NSManagedObject] {

                print ("Note:")
                if let designation = result.value(forKey: "designation") {
                    print("Designation: \(designation)")
                }

                  context.delete(result)

                 do {
                     try context.save()
                 } catch {
                     print("failed to delete note")
                 }   
            }
        }
    } catch {
        print ("Error in do")
    }

If I do something like this with an entity atribute it works ok. But with objectID (NSManagedObjectID) it's not working and app crashes. Any tips how to fix this please?

EDIT: This is the crash message: "Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: 'keypath objectID not found in entity ' (...) libc++abi.dylib: terminating with uncaught exception of type NSException (lldb) "

I see I cannot use objectID in predicate.... I tried to use SELF and it doesn't work....

H.N.
  • 1,207
  • 2
  • 12
  • 28

0 Answers0