是否可以插入新的核心数据记录,关系完整且没有NSManagedObject
子类?
我的设置是这样的:
目前的代码是:
NSManagedObjectContext *context = [self managedObjectContext];
NSManagedObject *author = [NSEntityDescription
insertNewObjectForEntityForName:@"Author"
inManagedObjectContext:context];
[author setValue:@"Jim" forKey:@"name"];
[author setValue:@"jim@g.com" forKey:@"email"];
NSManagedObject *topic = [NSEntityDescription
insertNewObjectForEntityForName:@"Topic"
inManagedObjectContext:context];
[topic setValue:@"Auto" forKey:@"title"];
NSManagedObject *post = [NSEntityDescription
insertNewObjectForEntityForName:@"Post"
inManagedObjectContext:context];
[post setValue:@"Test Bank" forKey:@"body"];
[post setValue:[NSDate date] forKey:@"creationDate"];
[post setValue:@"Testland" forKey:@"title"];
NSError *error;
if (![context save:&error]) {
NSLog(@"Whoops, couldn't save: %@", [error localizedDescription]);
}
这显然没有添加任何关系......我在另一篇SO帖子中看到了这个:
[[post mutableSetValueForKey:@"Author"] addObject:author];
但这会产生unrecognized selector sent to instance
错误
答案 0 :(得分:1)
首先,属性/关系名称具有案例敏感性(因此@"Author"
使用@"author"
而不是Post
。)
您的关系从Author
到[post setValue:author forKey:@"author"];
的基数是:to-one因此:
Author
应该设定关系。
(可变集合版本的工作方式为Post
到{{1}},其中基数为多数)