0

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

当我向 Dagbok 实体添加新帖子时,我希望它与来自 Valla 实体的帖子相关,这些帖子我存储在 FetchRequest 的 NSArray 中。

现在的代码只是向 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 结果的数组中添加相关对象?

4

1 回答 1

0

如果您创建 NSManagedObject 子类来表示您的实体,而不是直接处理 NSManagedObject,生活会容易得多。为此,在模型中为您的类添加一个名称(实体的“类”属性),例如将 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]];
于 2013-10-02T23:05:01.413 回答