5

我有两个核心数据实体,ArticlesFavorite. Articles与 具有多对多关系Favorite。首先,我Articles成功插入了所有对象。

现在,我试图在“收藏夹”实体中插入 ArticleID,但我不能。要么以空关系插入记录,要么以“文章”实体中的新记录插入记录。

我认为我应该先获取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) { 
        // ?????????????????????????

    }

}

任何建议,将不胜感激。

4

2 回答 2

4

Article首先,确保您在和之间具有互惠关系,即双向关系Favorite。像这样的东西:

Article{
  favorites<-->>Favorite.article
}

Favorite{
  article<<-->Article.favorites
}

在 Core Data 中定义互惠关系意味着从一侧设置关系会自动为另一侧设置关系。

因此,要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对象已经存在,您将首先获取对象,但设置关系的工作方式完全相同。

关键是确保您具有互惠关系,以便托管对象上下文知道在两个对象中设置关系。

于 2011-05-04T13:25:02.177 回答
0

我通过创建新的 Article 对象来解决它:

Articles *NewObj = [fetchedObjects objectAtIndex:0];

并用它来插入关系:

    [Fav setFavArticles:NewObj];
     [NewObj setArticlesFav:Fav];

非常感谢TechZen..

于 2011-05-06T14:21:54.867 回答