没有Subclassed NSManagedObject的关系核心数据插入

时间:2014-04-12 04:17:19

标签: objective-c core-data nsmanagedobject unrecognized-selector

是否可以插入新的核心数据记录,关系完整且没有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错误

1 个答案:

答案 0 :(得分:1)

首先,属性/关系名称具有案例敏感性(因此@"Author"使用@"author"而不是Post。)

您的关系从Author[post setValue:author forKey:@"author"]; 的基数是:to-one因此:

Author

应该设定关系。

(可变集合版本的工作方式为Post到{{1}},其中基数为多数)