0

我的模型有两个实体ArtistAlbum,并且Album有一个Artist实例成员。我使用以下代码预先填充了我的模型,但只找到了最后一个 Album ,即ablum3Artist Beatles. 对于album1, 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.

artist是 Artist 的逆 rel。一对一的基数。这是必需的,因为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 回答