2016-05-20 155 views
0

我遇到了與一對多關係相關的CoreData問題。NSManagedObjects問題之間的實體關係

實體1 - Authors與實體2具有一對多的關係 - Books。我認爲BooksAuthors有一對一的關係。

由於每個作家的多本書籍的作者對象我有

@property (nonatomic, retain) NSSet *book; 

書中對象相應的屬性是:

@property (nonatomic, retain) Authors *author; 

當來自服務器的應用程序下載的書籍通過API,在保存圖書後,我正在嘗試保存作者並使用以下代碼將作者與作者相關聯:

NSEntityDescription *entity = [NSEntityDescription entityForName:@"Books" inManagedObjectContext:self.managedObjectContext]; 

NSManagedObject *record = [[NSManagedObject alloc] initWithEntity:entity insertIntoManagedObjectContext:self.managedObjectContext]; 
record setValue:bookname forKey:@"bookname"]; 

if ([self.managedObjectContext save:&error]) { 
    Authors *newAuthor = [NSEntityDescription insertNewObjectForEntityForName:@"Authors" inManagedObjectContext:self.managedObjectContext]; 
         newAuthor.aid = authorid;      
         newAuthor.book = record; 
} 

此代碼爲我工作了一對一的關係,但在這種情況下,拋出下面的異常錯誤:

'NSInvalidArgumentException', reason: 'Unacceptable type of value for 
to-many relationship: property = "book"; desired type = NSSet; given 
type = Books; 

任何人都可以建議如何解決這一問題?

更新:

我也試過圍繞切換它來閱讀:

record.author = newAuthor; 

但是這給了錯誤

"property 'author' not found on object of type NSManagedObject"

雖然有這樣的Books對象定義的屬性(如如上所示)。

回答

0

由於book屬性是一個集合,CoreData應創建了一個Authors方法,如addBookObject:。在創建自定義實體類時,應該有一個名稱類似於「Authors + CoreDataProperties.h」的文件。在那裏查看定義的方法。

如果您使用Books而不是NSManagedObject,您的第二個選項也應該可以工作。 即:

Books *record = [[NSManagedObject alloc] initWithEntity:entity insertIntoManagedObjectContext:self.managedObjectContext]; 
+0

對不起,是密集的,但我一直在打我的頭在這一段時間...書*記錄= ???? – zztop

+0

如果核心數據創建的方法是這個引擎蓋下還是我應該做些什麼? – zztop

+0

我試圖解決這個問題。讓我知道我們是如何做的。 :) –

0

U可以產生NSManagedObject子類,以後只需創建幾個對象,一組關係和保存上下文一次,成才,如:

NSEntityDescription *entity = [NSEntityDescription entityForName:@"Book" inManagedObjectContext:self.context]; 
Book *newBook = [[Book alloc] initWithEntity:entity insertIntoManagedObjectContext:self.context]; 
newBook.bookName = @"My new book"; 

NSEntityDescription *entity2 = [NSEntityDescription entityForName:@"Record" inManagedObjectContext:self.context]; 
Record *newRecord = [[Record alloc] initWithEntity:entity2 insertIntoManagedObjectContext:self.context]; 
newRecord.name = @"New record"; 

newBook.record = newRecord; 
[newRecord addBook:[NSSet setWithObject:newBook]]; 

[self.context save:nil]; 

這是樣品分貝象下面這樣:

enter image description here

要自動生成類 - 選擇* .xcdatamodel文件中的實體並按下File-> New - >文件選擇CoreData部分和NSManagedObject子類,按嚮導步驟操作。

您將得到類似

enter image description here

甚至更​​多:

enter image description here

很好的教程ü也可以發現here