【发布时间】:2017-03-29 02:06:32
【问题描述】:
我在 Core Data 中有一个简单的 Person 实体,我注意到在添加数据时,每一行都会自动生成一个唯一的 PK,称为 objectID
我希望使用 objectID 检索记录,但出现以下错误:
由于未捕获的异常而终止应用程序 'NSInvalidArgumentException',原因:'keypath objectID not found in 实体 '
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!)")
}
}
}
【问题讨论】: