0

我四处寻找类似的东西,但没有运气,所以我将尝试解释我的麻烦并粘贴一些代码。我有一个使用核心数据的应用程序,我可以从它们各自的文本字段中保存和检索数据,但我的(与许多关系)除外。我相信这些被保存并在获取时作为集合返回。我已经阅读了 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]

4

1 回答 1

0

根据您的后续评论,Place 与 Section 实际上没有一对多关系,而 Section 与 Group 实际上也没有一对多关系。相反,Group 与 Section 具有一对多关系(部分),而部分的逆对 1 关系称为组。此外,Section 与 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 类直接访问字段,如果您喜欢这种方式,它也应该可以工作。

于 2011-11-17T16:41:30.413 回答