首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >core-data :只有最后一个对象可以在循环中正确初始化

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

Stack Overflow用户
提问于 2012-07-14 21:16:38
回答 1查看 106关注 0票数 0

我的模型有两个实体ArtistAlbumAlbum有一个Artist实例成员。我使用下面的代码来预先填充我的模型,但只发现最后一个专辑,即ablum3,与Artist Beatles建立了正确的关联。对于album1album2artist字段为nil

一定有什么我没注意到的地方...

代码语言:javascript
复制
//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"];
}
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2012-07-14 22:02:46

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

所以,这个模型适用于我。

Album相比,albums是一种多对关系。此外,它是可选的,您可以使用不带AlbumArtist

artist是艺术家的反向版本。一对一基数。它是必需的,因为没有Artist就不能有Album

代码如下:

代码语言:javascript
复制
- (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]的上下文

代码语言:javascript
复制
- (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();
        } 
    }
}

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

希望这能有所帮助。

票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/11484075

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档