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

后端 未结 2 1523
生来不讨喜
生来不讨喜 2021-01-17 10:37

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

let fetchedId = poi.objectID.URIRepresentation()

Now

相关标签:
2条回答
  • 2021-01-17 11:08

    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)
    
    0 讨论(0)
  • 2021-01-17 11:11

    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.

    0 讨论(0)
提交回复
热议问题