My XML import requires that I check for an existing object before I insert. In other words I need to hold each record in a temporary managed data object before I determine whether to save it or not. *** NOTE: Please refer to the last answer in this thread:
Is there a way to instantiate a NSManagedObject without inserting it?
I took the approach of the last answer in the link above using insertIntoManagedObjectContext:nil which put the incoming one-record into a temporary object without a context.
Within my import I have two tables: a one-table record and multiple related-many record following right behind it. This works great except that I have related-many records following this.
Right now I’m inserting the many-table records into their own managed object with nil also. The question is when I’m about to save the one record, I also have multiple related many objects I’ve created. How do I save the many records? Can I fetch them from a nil context and loop through them?
Here is the code for the beginning of a new record:
// Incoming record is for the one table.
if ([elementName isEqualToString: self.xmlRecordTagDelimiter]) {
NSEntityDescription *entity = [NSEntityDescription entityForName:self.xmlEntityName inManagedObjectContext:xmlManagedObjectContext];
self.xmlCurrentRecordTempObject = [[NSManagedObject alloc] initWithEntity:entity insertIntoManagedObjectContext:nil];
thisTagIsForManyTable = NO;
}
// Incoming record is for the many table.
if ([elementName isEqualToString: self.xmlManyRecordTagDelimiter]) {
NSEntityDescription *entity = [NSEntityDescription entityForName:self.xmlRelatedManyEntityName inManagedObjectContext:xmlManagedObjectContext];
self.xmlCurrentManyRecordTempObject = [[NSManagedObject alloc] initWithEntity:entity insertIntoManagedObjectContext:nil];
thisTagIsForManyTable = YES;
}
And the code where I’m about to save a one-table record into a contect:
[self.managedObjectContext insertObject:self.xmlCurrentRecordTempObject];
// Store what we imported already.
if (![self.xmlManagedObjectContext save:&error]) {
...... snip.....
}
Thanks
It sounds like you’re thinking of a
nilcontext as yet another managed object context. This is not the case. When you passnilas the context toinitWithEntity:insertIntoManagedObjectContext:you are requesting that the created managed object not be inserted into any context. It is not inserted into a managed object context callednil. It is not inserted into any managed object context.So, when you ask whether you can fetch your many objects from the
nilcontext, the answer is “no.” This is because there is nonilcontext.However,
NSManagedObjects are objects. You could store your many objects in an array and, when you’re about to save, just loop through the array, find the many objects that you want to save, and only insert those into your context.