我的 XML 导入要求我在插入之前检查现有对象。换句话说,在确定是否保存之前,我需要将每条记录保存在临时托管数据对象中。*** 注意:请参阅此线程中的最后一个答案:
有没有办法在不插入的情况下实例化 NSManagedObject?
我采用了上面链接中最后一个答案的方法,使用 insertIntoManagedObjectContext:nil 将传入的单记录放入没有上下文的临时对象中。
在我的导入中,我有两个表:一个表记录和紧随其后的多个相关多记录。除了我有相关的许多记录之外,这很好用。
现在我也用 nil 将多表记录插入到他们自己的托管对象中。问题是当我要保存一条记录时,我还创建了多个相关的许多对象。如何保存许多记录?我可以从零上下文中获取它们并循环它们吗?
以下是新记录开始的代码:
// 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;
}
以及我即将将单表记录保存到 contect 中的代码:
[self.managedObjectContext insertObject:self.xmlCurrentRecordTempObject];
// Store what we imported already.
if (![self.xmlManagedObjectContext save:&error]) {
...... snip.....
}
谢谢