Core data 核心数据添加与fetchRequest结果相关的新实体post

Core data 核心数据添加与fetchRequest结果相关的新实体post,core-data,many-to-many,relationship,Core Data,Many To Many,Relationship,我的CoreData模型中有两个实体,“Valla”和“Dagbok”,它们与多对多关系相关 当我向Dagbok实体添加一个新帖子时,我希望它与我从FetchRequest存储在NSArray中的Valla实体的帖子相关 现在的代码只是向Dagbok添加了一个帖子 - (void)initDagbokDBWithText:(NSString *)text header:(NSString *)header degree:(int)degree weather:(NSString *)weathe

我的CoreData模型中有两个实体,“Valla”和“Dagbok”,它们与多对多关系相关

当我向Dagbok实体添加一个新帖子时,我希望它与我从FetchRequest存储在NSArray中的Valla实体的帖子相关

现在的代码只是向Dagbok添加了一个帖子

- (void)initDagbokDBWithText:(NSString *)text header:(NSString *)header degree:(int)degree weather:(NSString *)weather farg:(NSString *)farg
{
    AppDelegate *appdelegate = [[UIApplication sharedApplication]delegate];
    context = [appdelegate managedObjectContext];

    NSEntityDescription *entitydesc = [NSEntityDescription entityForName:@"Dagbok" inManagedObjectContext:context];
    NSManagedObject *newDagbok = [[NSManagedObject alloc] initWithEntity:entitydesc insertIntoManagedObjectContext:context];

    //NSRelationshipDescription *dagbokRelation = [[NSRelationshipDescription alloc] init];
    //NSRelationshipDescription *vallaRelation = [[NSRelationshipDescription alloc] init];

    [newDagbok setValue:text forKey:@"text"];
    [newDagbok setValue:header forKey:@"header"];
    [newDagbok setValue:[NSNumber numberWithInt:degree] forKey:@"degree"];
    [newDagbok setValue:weather forKey:@"weather"];
    [newDagbok setValue:farg forKey:@"colorCode"];

    NSError *error;
    if(![context save:&error])
    {
        NSLog(@"Whoops : %@", [error localizedDescription]);
    }

}

如何从具有fetchRequest结果的数组中添加相关对象?

如果您创建NSManagedObject子类来表示您的实体,而不是直接处理NSManagedObject,那么生活会轻松得多。为此,请在模型中为类添加名称(实体的“class”属性),例如将Valla设置为VallaEntity。然后XCode可以自动生成这些类,这些类将具有简化代码的属性和方法,例如

DagbokEntity *newDagbok = [[NSManagedObject alloc] initWithEntity:entitydesc insertIntoManagedObjectContext:context];

newDagbok.text = text;
newDagbok.header = header;
newDagbok.degree = [NSNumber numberWithInt:degree];
newDagbok.weather = weather;
newDagbok.colorCode = farg;
[newDagbok addVallas:[NSSet setWithArray:arrayOfRelatedVallas]];