问题描述
我有一个来自coredata的对象,然后我从这些对象之一获取objectId:
I have a list objects from coredata and then I get objectId from one of those objects:
let fetchedId = poi.objectID.URIRepresentation()
现在我需要获取这个特定objectID的实体。
我试过像:
Now I need to get entity for this specific objectID.And I tried something like:
let entityDescription = NSEntityDescription.entityForName("Person", inManagedObjectContext: managedObjectContext!);
let request = NSFetchRequest();
request.entity = entityDescription;
let predicate = NSPredicate(format: "objectID = %i", fetchedId);
request.predicate = predicate;
var error: NSError?;
var objects = managedObjectContext?.executeFetchRequest(request,
error: &error)
但我收到错误:
Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: 'keypath objectID not found in entity <NSSQLEntity Person id=4>'
推荐答案
您无法使用NSFetchRequest的谓词查询NSManagedObject的任意属性。这只适用于在您的实体中定义的属性。
You can't query arbitrary properties of the NSManagedObject with a predicate for a NSFetchRequest. This will only work for attributes that are defined in your entity.
NSManagedObjectContext有两种方法来检索具有NSManagedObjectID的对象。如果对象在上下文中不存在,则第一个引发异常:
NSManagedObjectContext has two ways to retrieve an object with an NSManagedObjectID. The first one raises an exception if the object does not exist in the context:
managedObjectContext.objectWithID(objectID)
第二个将通过返回nil失败:
The second will fail by returning nil:
var error: NSError?
if let object = managedObjectContext.existingObjectWithID(objectID, error: &error) {
// do something with it
}
else {
println("Can't find object \(error)")
}
b $ b
如果你有一个URI而不是NSManagedObjectID,你必须先把它转换为NSManagedObjectID。 persistStoreCoordinator用于此:
If you have a URI instead of a NSManagedObjectID you have to turn it into a NSManagedObjectID first. The persistentStoreCoordinator is used for this:
let objectID = managedObjectContext.persistentStoreCoordinator!.managedObjectIDForURIRepresentation(uri)
这篇关于如何通过其objectID获取核心数据实体?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!