0

私の CoreData モデルには「Valla」と「Dagbok」という 2 つのエンティティがあり、これらは多対多の関係で関連付けられています。

Dagbok-entity に新しい投稿を追加するときに、FetchRequest から NSArray に保存する Valla-entity からの投稿に関連付けたいと考えています。

現在のコードは、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 に答える