0

私のモデルには と の 2 つのエンティティがArtistありAlbum、インスタンス メンバーAlbumがあります。Artist次のコードを使用してモデルを事前設定しましたが、最後の Album しか見つかりませんでした。つまり、ablum3との正しい関連付けが設定されていますArtist Beatlesalbum1の場合album2、、artistフィールドはnilです。

私が気付かなかった何かが間違っているに違いない...

//create  an artist
NSManagedObject *artist = [NSEntityDescription
                           insertNewObjectForEntityForName:@"Artist"
                           inManagedObjectContext:__managedObjectContext]; 

[artist setValue:@"Beatles" forKey:@"name"];

//populate the data
NSArray *albums = [NSArray arrayWithObjects:@"album1",@"album2",@"album3", nil];
for (NSString *title in albums){
    //populate the data
    NSManagedObject *album = [NSEntityDescription
                              insertNewObjectForEntityForName:@"Album"
                              inManagedObjectContext:__managedObjectContext]; 

    [album setValue:title forKey:@"title"];
    [album setValue:artist forKey:@"artist"];
}
4

1 に答える 1

2

これ以上の詳細がなければ、何が起こっているのかを知ることは困難です。私はあなたが書いたことのモデルを理解しようとします。

だから、このモデルは私のために働く

ここに画像の説明を入力

albumsは との対多関係Albumです。さらに、それはオプションでありArtist、なしで持つことができますAlbum

artistArtist の逆相関です。1 対 1 のカーディナリティ。Albumなしでは を持てないため、必須ですArtist

ここにコード:

- (void)populateDB
{
    //create  an artist
    NSManagedObject *artist = [NSEntityDescription
                               insertNewObjectForEntityForName:@"Artist"
                               inManagedObjectContext:[self managedObjectContext]]; 

    [artist setValue:@"Beatles" forKey:@"name"];

    //populate the data
    NSArray *albums = [NSArray arrayWithObjects:@"album1",@"album2",@"album3", nil];
    for (NSString *title in albums){
        //populate the data
        NSManagedObject *album = [NSEntityDescription
                                  insertNewObjectForEntityForName:@"Album"
                                  inManagedObjectContext:[self managedObjectContext]]; 

        [album setValue:title forKey:@"title"];
        [album setValue:artist forKey:@"artist"];
    }
}

を呼び出した後populatedDB、コンテキスト呼び出しを保存します[self saveContext]

- (void)saveContext {
    NSError *error = nil;
    NSManagedObjectContext *moc = [self managedObjectContext];
    if (moc != nil) {
        if ([moc hasChanges] && ![moc save:&error]) {
             // Replace this implementation with code to handle the error appropriately.
             // abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development. 
            NSLog(@"Unresolved error %@, %@", error, [error userInfo]);
            abort();
        } 
    }
}

モデルの手配が必要な場合はお知らせください。

それが役立つことを願っています。

于 2012-07-14T14:02:46.267 に答える