How to Get Core Data Object from Specific Object Id

How to get Core Data object from specific Object ID?

You want:

-(NSManagedObject *)existingObjectWithID:(NSManagedObjectID *)objectID
error:(NSError **)error

Fetches the object from the store that has that ID, or nil if it doesn't exist.

(Be aware: there are two methods on NSManagedObjectContext with similar-seeming names that tripped me up. To help keep them straight, here's what the other two do:

-(NSManagedObject *)objectWithID:(NSManagedObjectID *)objectID

...will create a fault object with the provided objectID, whether or not such an object actually exists in the store. If it doesn't exist, anything that fires the fault will fail unless you insert the object first with NSManagedObjectContext's insertObject:. The only use I've found for this is copying objects from store to store while preserving ObjectIDs.

-(NSManagedObject *)objectRegisteredForID:(NSManagedObjectID *)objectID

...will return the object that has that ID, if it has been fetched from the store by this managedObjectContext. If anyone knows what this method is useful for, please comment.)

[eta.: Another important difference between the first method and the other two is that existingObjectWithID:error: never returns a fault; it always fetches the whole object for you. If you're trying to avoid that (e.g. working with an expensive-to-fetch object with a big blob property), you have to be clever with objectWithID: or objectRegisteredForID:, which don't fire faults; or use a properly configured fetch request.]

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

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)

IOS/Objective-C/Core-data: how to get object from objectID

Yes, both are methods of the NSManagedObjectContext therefore you need to call this method on an NSManagedObjectContext instance where this object is in.

See also https://developer.apple.com/library/mac/documentation/Cocoa/Reference/CoreDataFramework/Classes/NSManagedObjectContext_Class/index.html#//apple_ref/occ/instm/NSManagedObjectContext/objectWithID:

Core Data - fetch object with keypath and Object ID

You should get the object with existingObject from the Object ID and use that in the predicate.

if let myPerson = context.existingObject(with: myPersonObjectID) {
request.predicate = NSPredicate(format: "person = %@", myPerson)
}

Core data, how to get NSManagedObject's ObjectId when NSFetchRequest returns NSDictionaryResultType?

Yes you can, using the very nifty but badly-documented NSExpressionDescription class. You need to add a properly-configured NSExpressionDescription object to the array of NSPropertyDescription objects you set via setPropertiesToFetch: for your NSFetchRequest.

For example:

NSExpressionDescription* objectIdDesc = [[NSExpressionDescription new] autorelease];
objectIdDesc.name = @"objectID";
objectIdDesc.expression = [NSExpression expressionForEvaluatedObject];
objectIdDesc.expressionResultType = NSObjectIDAttributeType;

myFetchRequest.propertiesToFetch = [NSArray arrayWithObjects:objectIdDesc, anotherPropertyDesc, yetAnotherPropertyDesc, nil];
NSArray* fetchResults = [myContext executeFetchRequest:myFetchRequest error:&fetchError];

You should then have a @"objectID" key in the the dictionaries you get back from your fetch request.

Core data - Searches for a single object that has a given identifier

The getSong method cannot work, the predicate is wrong, the fetch returns always an array, and it's highly recommended to specify the static type of the entity rather than unspecified NSFetchRequestResult

And as song is obviously an NSManagedObject subclass you cannot create an instance with the default initializer Song(). Better return an optional

func getSong(number: String) -> Song? {
guard let songNumber = Int64(number) else { return nil }
let context = container.viewContext
let request = NSFetchRequest<Song>(entityName: "Song")
request.predicate = NSPredicate(format: "number == %ld", songNumber)

do {
return try context.fetch(request).first
} catch {
print(error)
return nil
}
}


Related Topics



Leave a reply



Submit