如何在不复制的情况下插入与另一个相关的核心数据记录
问题描述:
我有两个核心数据实体Articles
和Favorite
。 Articles
与Favorite
有多对多关系。首先,我成功插入了所有的Articles
对象。如何在不复制的情况下插入与另一个相关的核心数据记录
现在,我试图插入ArticleID在“收藏”实体,但我不能。无论是记录是插入一个空的关系,或者它被插入“Articles”实体中的新记录。
我认为我应该首先获得Articles
实体的相关记录,然后使用它插入Favorite
,但我不确定如何执行此操作。我目前的代码:
NSManagedObjectContext *context =[appDelegate managedObjectContext] ;
favorite *Fav =[NSEntityDescription insertNewObjectForEntityForName:@"favorite" inManagedObjectContext:context];
Articles * Article = [NSEntityDescription insertNewObjectForEntityForName:@"Articles" inManagedObjectContext:context];
NSError *error;
NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];
NSEntityDescription *entity = [NSEntityDescription
entityForName:@"Articles" inManagedObjectContext:context];
[fetchRequest setEntity:entity];
NSPredicate *secondpredicate = [NSPredicate predicateWithFormat:@"qid = %@",appDelegate.GlobalQID ];
NSPredicate *thirdpredicate = [NSPredicate predicateWithFormat:@"LangID=%@",appDelegate.LangID];
NSPredicate *comboPredicate = [NSCompoundPredicate andPredicateWithSubpredicates:[NSArray arrayWithObjects: secondpredicate,thirdpredicate, nil]];
[fetchRequest setPredicate:comboPredicate];
NSArray *fetchedObjects = [context executeFetchRequest:fetchRequest error:&error];
for (NSManagedObject *info in fetchedObjects) {
// ?????????????????????????
}
}
任何意见,将不胜感激。
答
我解决它通过创造新的Article对象:
Articles *NewObj = [fetchedObjects objectAtIndex:0];
,并用它来插入关系:
[Fav setFavArticles:NewObj];
[NewObj setArticlesFav:Fav];
非常感谢TechZen ..
答
首先,确保您在Article
和Favorite
之间有双向关系。事情是这样的:
Article{
favorites<-->>Favorite.article
}
Favorite{
article<<-->Article.favorites
}
定义中核心数据的互惠关系是指设置从一个侧面关系自动设置它为其他。
因此,设置新的Favorite
对象为新创建的Article
对象,你只想:
Favorite *fav =[NSEntityDescription insertNewObjectForEntityForName:@"favorite" inManagedObjectContext:context];
Articles *article = [NSEntityDescription insertNewObjectForEntityForName:@"Articles" inManagedObjectContext:context];
[article.addFavoriteObject:fav];
//... or if you don't use custom NSManagedObject subclasses
[[article mutableSetValueForKey:@"favorites"] addObject:fav];
如果两个Article
对象或Favorite
对象已经存在,你会首先提取对象,但设置关系将以完全相同的方式工作。
关键是要确保您有互惠关系,以便托管对象上下文知道在两个对象中设置关系。
感谢TechZen .. 我有已经反转文章和最喜欢的关系.. 文章的对象先前插入,现在我想插入相关的收藏对象。 我已经将这行添加到循环中: [[Fatwa mutableSetValueForKey:@“FavArticle”] addObject:Fav]; 并获取此错误: 由于未捕获的异常'NSUnknownKeyException',原因:'[ valueForUndefinedKey:]终止应用程序:实体文章不是密钥值编码兼容的密钥“FavFArticle”。 如何使用fetched Articles对象插入喜欢的对象?? – smaiibnauf 2011-05-04 22:47:12
错误表示您没有为'Articles'实体/类定义的/ spelled“FavArticle”属性。这通常只是拼写错误导致您拼错关键名称的结果,例如真实姓名就像“favArticle”或“favArticles”。 – TechZen 2011-05-05 17:38:19
为什么从文章到收藏的关系是1-> N? – 2011-12-05 12:47:01