在我的应用程序中,我需要创建NSManagedObject
子类的实例而不将其插入上下文中。我这样做:
NSManagedObjectModel *managedObjectModel = self.managedObjectContext.persistentStoreCoordinator.managedObjectModel;
NSEntityDescription *parentEntity = [[managedObjectModel entitiesByName] objectForKey:@"Parent"];
Parent *parent = (Parent *)[[NSManagedObject alloc] initWithEntity:parentEntity
insertIntoManagedObjectContext:nil];
parent.name = @"Jonny";
NSEntityDescription *childEntity = [[managedObjectModel entitiesByName] objectForKey:@"Child"];
Child *child = (Child *)[[NSManagedObject alloc] initWithEntity:childEntity insertIntoManagedObjectContext:nil];
child.name = @"Kim";
[parent child];
当用户决定存储对象时,我这样做:
[self.managedObjectContext insertObject:self.parent];
for (Child *child in self.parent.children) {
[self.managedObjectContext insertObject:child];
}
NSError *err = nil;
if (![self.managedObjectContext save:&err]) {
NSLog(@"error: couldn't save managed object context. %@", err);
}
当我在这里查看children
属性的长度时,它总是> 0
。到目前为止一切都很好。
但是,在我的下一个视图控制器中,当我尝试检索这些属性时:
- (NSMutableArray *)fetchObjects {
NSMutableArray *parents = [[NSMutableArray alloc] init];
NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];
NSEntityDescription *entity = [NSEntityDescription entityForName:@"Parent" inManagedObjectContext:self.managedObjectContext];
[fetchRequest setEntity:entity];
NSError *error = nil;
NSArray *result = [self.managedObjectContext executeFetchRequest:fetchRequest error:&error];
if (error) {
NSLog(@"Unable to execute fetch request.");
NSLog(@"%@, %@", error, error.localizedDescription);
}
else {
for (id parent in result) {
Parent *parent = (Parent *)parent;
[parents addObject:parent];
}
}
return favorites;
}
每个父级的children
属性的长度始终为0
。似乎无法弄清楚为什么。提前谢谢。
答案 0 :(得分:0)
创建托管对象并在以后保存或丢弃托管对象的常用模式是将它们插入临时上下文。
使您的主上下文成为此临时上下文的父上下文,然后save
或将其丢弃。