Create Core Data Relationship Without Fetching the Existing Object
We have a process that needs to update an existing core data store to add children relationships. We already have an entity called human but now we have added the ability to link humans as parents of other humans. So far the way we are doing this is to first fetch the human that will be the parent and then fetch the humans that will be the children, and then add the children to an NSSet* property called "children" on the parent object. This however requires fetching both the children AND parent from core data, which is slow, especially given that we can have potentially tens of thousands of objects.
The parent / child relationship is a new feature and we get the relationship data from an xml stream from a server. It basically contains our integer id for each human and a list of integers for that human of their children.
Is there a way to create this relationship without fetching the children as well? Can you create a relationship like this just using a NSManagedObjectID or some other identifier? Or do you have to have the entire object fetched from core data? One thing we know for certain is that all human objects are guaranteed to be in core dat开发者_运维技巧a, so there will never be a need to create new human objects, they are all already in the core data store.
If you have the actual managedObjectIDs of the objects, you can use -[NSMangedObjectContext objectForID:]
to get only that particular object from the DB. That would be faster than fetching each object.
However, there is no way of setting a relationship without having both objects.
The "fetched property" is meant to help with problems like this, it allows you to access the related object as if it's a direct relationship, but it doesn't do the fetch until it is requested. They are only one way relationships.
See: Fetched Properties v Relationships (Core Data - iPhone)
There is no way to set the value of a to-many relationship without causing a fault. Invoking either the object level setter (e.g. addParent:(Human *)parent) or manipulating the set directly will trigger a fault. CoreData has to do this to ensure relationship integrity.
[NSManagedObjectContext objectForID:] will return a fault to you, which you can then use to pass as an object to the relationship, but as soon as you set one side of the relationship the object will fault anyway.
I'm not sure how much data you're working with, but if your entities are light enough you could theoretically fetch them all in to memory and do your sorting / searching there (NSArray + NSPredicate).
精彩评论