核心数据 - 与许多关系 - 在集合方面遇到问题

时间:2011-11-17 16:24:01

标签: core-data entity-relationship one-to-many nsset

我一直在寻找类似的东西而没有运气,所以我将尝试解释我的麻烦并粘贴一些代码。我有一个使用Core Data的应用程序,我可以保存和检索来自各自textFields的数据,但我(对很多关系)除外。我相信它们会被保存并在获取时作为集合返回。我已经阅读了NSSet并查看了一些代码,但仍然不明白如何编写代码。

感谢您的帮助。 哈德森

- (IBAction) findContact
{
AppDelegate *appDelegate = [[UIApplication sharedApplication]delegate];
NSManagedObjectContext *context = [appDelegate managedObjectContext];

NSEntityDescription *entity = [NSEntityDescription entityForName:@"Place" 
                                              inManagedObjectContext:context];
NSFetchRequest *fetchRequest = [[NSFetchRequest alloc]init];
[fetchRequest setEntity:entity];
NSPredicate *pred = [NSPredicate predicateWithFormat:@"placeName = %@", placeName.text];
[fetchRequest setPredicate:pred];
Place *matches = nil;
NSError *error;
NSArray *objects = [context executeFetchRequest:fetchRequest error:&error];
if ([objects count] == 0) {
    status.text = @"No matches";
}else{

    matches = [objects objectAtIndex:0];
    address.text = [matches valueForKey:@"address"];
    city.text = [matches valueForKey:@"city"];
    state.text = [matches valueForKey:@"state"];
    zip.text = [matches valueForKey:@"zip"];
    phone1.text = [matches valueForKey:@"phone1"];
    email.text = [matches valueForKey:@"email"];
    website.text = [matches valueForKey:@"website"];
    phone2.text = [matches valueForKey:@"phone2"];
    about.text = [matches valueForKey:@"about"];
    photoName.text = [[matches photo]valueForKey:@"photoName"];
    status.text = [NSString  stringWithFormat:@"%d matches found", [objects count]];
    NSSet *groupForSections = [groupForSections valueForKey:@"sections"];
    for (Group *group in groupForSections) {
        NSLog(@"group name = %@", [groupForSections valueForKey:@"groupName"]);
        groupName.text = [group valueForKey:@"groupName"];
    NSSet *sectionForPlaces = [sectionForPlaces valueForKey:@"places"];
    for (Section *section in sectionForPlaces) {
        sectionName.text = [section valueForKey:@"sectionName"];
        NSLog(@"section name = %@", [section valueForKey:@"sectionName"]);
        }
    }
    }
    }

![在此处输入图片说明] [1]

1 个答案:

答案 0 :(得分:0)

根据您的后续评论,Place实际上与Section没有多对多的关系,而且Section实际上与Group没有多对多的关系。相反,Group具有与Section有关的多对多关系(部分),而部分的反向-1关系被称为组。此外,Section具有to-many关系(地点),其中Place和Place的反向-1关系称为section。

如果所有这些假设都是正确的(并且没有看到您的模型,那么很难知道这是否正确),您的代码现在应该是这样的:

NSManagedObject *sectionForPlace = [matches valueForKey:@"section"]; 
sectionName.text = [sectionForPlace valueForKey:@"sectionName"];

NSManagedObject *groupForSection = [sectionForPlace valueForKey:@"group"];
gromName.text = [groupForSection valueForKey:@"groupName"];

此代码不会通过您创建的NSManagedObject类直接访问这些字段,如果您喜欢这样,它也应该可以使用。