2011-05-04 24 views
5

我有兩個核心數據實體ArticlesFavoriteArticlesFavorite有多對多關係。首先,我成功插入了所有的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) { 
     // ????????????????????????? 

    } 

} 

任何意見,將不勝感激。

回答

0

我解決它通過創造新的Article對象:

Articles *NewObj = [fetchedObjects objectAtIndex:0]; 

,並用它來插入關係:

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

非常感謝TechZen ..

4

首先,確保您在ArticleFavorite之間有雙向關係。事情是這樣的:

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對象已經存在,你會首先提取對象,但設置關係將以完全相同的方式工作。

關鍵是要確保您有互惠關係,以便託管對象上下文知道在兩個對象中設置關係。

+0

感謝TechZen .. 我有已經反轉文章和最喜歡的關係.. 文章的對象先前插入,現在我想插入相關的收藏對象。 我已經將這行添加到循環中: [[Fatwa mutableSetValueForKey:@「FavArticle」] addObject:Fav]; 並獲取此錯誤: 由於未捕獲的異常'NSUnknownKeyException',原因:'[<文章0xc9dfec0> valueForUndefinedKey:]終止應用程序:實體文章不是密鑰值編碼兼容的密鑰「FavFArticle」。 如何使用fetched Articles對象插入喜歡的對象?? – smaiibnauf 2011-05-04 22:47:12

+0

錯誤表示您沒有爲'Articles'實體/類定義的/ spelled「FavArticle」屬性。這通常只是拼寫錯誤導致您拼錯關鍵名稱的結果,例如真實姓名就像「favArticle」或「favArticles」。 – TechZen 2011-05-05 17:38:19

+0

爲什麼從文章到收藏的關係是1-> N? – 2011-12-05 12:47:01

相關問題