我对核心数据的简单Person实体,我注意到,增加的数据时,每行是自动生成的唯一PK称为的objectID核心数据使用自动生成的主键PK
我希望检索使用记录的objectID,但我收到以下错误:
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)
}
}
}
调用上面的:
//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!)")
}
}
}
有趣的是,最好忽略主键并改用自己的值。 –
是的。核心数据通常通过关系维护参照完整性。这些将由内部私钥进行备份,但这是一个实现细节。使用核心数据时,请小心不要过多地考虑SQL,因为这不是一回事。 –