我有一个来自coredata的列表对象,然后我从其中一个对象获取objectId:
let fetchedId = poi.objectID.URIRepresentation()
Run Code Online (Sandbox Code Playgroud)
现在我需要为这个特定的objectID获取实体.我尝试过类似的东西:
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)
Run Code Online (Sandbox Code Playgroud)
但我得到错误:
Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: 'keypath objectID not found in entity <NSSQLEntity Person id=4>'
Run Code Online (Sandbox Code Playgroud)
Mat*_*uch 18
您不能使用NSFetchRequest的谓词来查询NSManagedObject的任意属性.这仅适用于实体中定义的属性.
NSManagedObjectContext有两种方法可以使用NSManagedObjectID检索对象.如果对象在上下文中不存在,则第一个引发异常:
managedObjectContext.objectWithID(objectID)
Run Code Online (Sandbox Code Playgroud)
第二个将失败返回nil:
var error: NSError?
if let object = managedObjectContext.existingObjectWithID(objectID, error: &error) {
// do something with it
}
else {
println("Can't find object \(error)")
}
Run Code Online (Sandbox Code Playgroud)
如果您有URI而不是NSManagedObjectID,则必须先将其转换为NSManagedObjectID.persistentStoreCoordinator用于此:
let objectID = managedObjectContext.persistentStoreCoordinator!.managedObjectIDForURIRepresentation(uri)
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
17805 次 |
| 最近记录: |