core-data:只能在循环中正确初始化最后一个对象

时间:2012-07-14 13:16:38

标签: objective-c ios core-data

我的模型有两个实体ArtistAlbum,而Album有一个Artist实例成员。我使用以下代码预先填充我的模型,但只找到最后一个相册,即ablum3,已与Artist Beatles建立了正确的关联。对于album1album2artist字段为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"];
}

1 个答案:

答案 0 :(得分:2)

没有进一步的细节,很难知道发生了什么。我试着理解你所写的模型。

所以,这个模型适合我

enter image description here

albums是与Album的多对多关系。此外,它是可选的,您可以Artist没有Album

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();
        } 
    }
}

如果您需要安排模型,请告诉我。

希望有所帮助。