【发布时间】:2011-03-06 04:25:27
【问题描述】:
我的 XML 导入要求我在插入之前检查现有对象。换句话说,在确定是否保存之前,我需要将每条记录保存在临时托管数据对象中。 *** 注意:请参考本帖最后一个答案:
Is there a way to instantiate a NSManagedObject without inserting it?
我采用了上面链接中最后一个答案的方法,使用 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.....
}
谢谢
【问题讨论】:
-
听起来你的数据模型可能不像你需要的那样设置。听起来你用 SQL 术语来思考 Core Data,这会导致悲伤。
标签: xml core-data import relationship nsmanagedobjectcontext