How can I get the main data object using objectID?

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

let fetchedId = poi.objectID.URIRepresentation() 

Now I need to get an object for this particular object identifier. 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 the error:

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

You cannot query arbitrary properties of an NSManagedObject with a predicate for NSFetchRequest. This will only work for attributes defined in your entity.

NSManagedObjectContext has two ways to retrieve an object using NSManagedObjectID. The first throws an exception if the object does not exist in context:

 managedObjectContext.objectWithID(objectID) 

The second will fail, 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 NSManagedObjectID, you must first transfer it to NSManagedObjectID. To do this, use persistentStoreCoordinator:

 let objectID = managedObjectContext.persistentStoreCoordinator!.managedObjectIDForURIRepresentation(uri) 
+12
source

What you get is not an object identifier, but a URI. The object identifier is part of the URI. You can set a persistent storage coordinator for an object identifier using - managedObjectIDForURIRepresentation: Having the object identifier, you can get the object from the context using, for example, -objectWithID: But please look at the documentation for these methods for some reason.

+1
source

Source: https://habr.com/ru/post/983864/


All Articles