16

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>'
Matthias Bauch
  • 89,811
  • 20
  • 225
  • 247
1110
  • 7,829
  • 55
  • 176
  • 334

2 Answers2

26

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)
Matthias Bauch
  • 89,811
  • 20
  • 225
  • 247
  • 4
    I think this is the wrong way around unless it has been changed in swift 3 - `context.existingObject(with: objectID)` throws, `context.object(with: objectID)` returns nil if not found – mbdavis Jan 26 '17 at 14:46
2

What you get is not the object ID, but the URI. The object ID is a part of the URI. You can ask the persistent store coordinator for the object ID with - managedObjectIDForURIRepresentation:. Having the object ID you can get the object from the context using for example -objectWithID:. But please look to the documentation, of this methods for some reasons.

Amin Negm-Awad
  • 16,582
  • 3
  • 35
  • 50