I have a simple Person entity in Core Data, I noticed that when adding data, each row is auto generated a unique PK called objectID
I wish to retrieve the records using the objectID but I am getting the following error:
Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: 'keypath objectID not found in entity < NSSQLEntity Person id=2 >'
func fetchPerson(withID personID: Int,
context: NSManagedObjectContext,
completion: @escaping ([Person]?) -> Void) {
let fetchRequest: NSFetchRequest<Person> = Person.fetchRequest()
let predicate = NSPredicate(format: "\(#keyPath(Person.objectID)) == \(personID)")
fetchRequest.predicate = predicate
//perform aynchronous operation:
context.perform {
do {
let persons = try fetchRequest.execute()
//success - return array of persons
completion(persons)
} catch {
//error - return nil
completion(nil)
}
}
}
Calling the above :
//fetch person with specific id:
let personID: Int = 2
fetchPerson(withID: personID, context: persistentContainer.viewContext) { (persons: [Person]?) in
if persons != nil {
print("Fetching person with personID: \(personID)")
for person in persons! {
print("Person: \(person.objectID) - \(person.firstName!) \(person.lastName!)")
}
}
}