【发布时间】:2016-09-17 16:45:32
【问题描述】:
我遇到了与一对多关系相关的 CoreData 问题。
实体 1 - Authors 与实体 2 - Books 具有一对多关系。我认为Books 与Authors 是一对一的关系。
由于我拥有的作者对象中每个作者有多本书
@property (nonatomic, retain) NSSet *book;
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;
但这会报错
“在 NSManagedObject 类型的对象上找不到属性‘作者’”
虽然Books对象中定义了这样一个属性(如上图)。
【问题讨论】:
标签: ios exception core-data relationship nsmanagedobject