2016-05-20 90 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