1110 1110 - 19 days ago 4
Swift Question

How can I get core data entity by it's objectID?

I have a list objects from coredata and then I get objectId from one of those objects:

let fetchedId = poi.objectID.URIRepresentation()


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)


But I get error:

Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: 'keypath objectID not found in entity <NSSQLEntity Person id=4>'

Answer

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 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) 

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)")
}

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)