iPhone核心数据关系

时间:2012-03-09 00:19:28

标签: iphone ios xcode core-data

我遇到了创建问题,并了解如何为这种情况创建核心数据模型。

(1)一个人可以有多只宠物(狗或猫的组合)。

(2)也可能有多个人。

我想通过Person实体并拉动每个人,每个宠物和那里的信息。

我不确定是否应该使用关系,或者如何在Core Data中设置此模型。我迅速记下了我认为模型看起来的选择器。我为了简单起见制作了这个模型,我的模型并不涉及猫和狗。

非常感谢任何建议或想法。

enter image description here

1 个答案:

答案 0 :(得分:11)

我很快为你准备了一个模型:

enter image description here

所以,基本上“人”是你的人,它与“宠物”有关系 - 这是一种“与众不同”的关系。一个人可以有多只宠物。

然后有一个“宠物”实体。它是一个抽象的实体,代表任何宠物,猫和狗。它与“人”的“宠物”呈反比关系。因此,从任何宠物,您可以随时追溯到相应的所有者。此外,“宠物”的每个子类都有一些共同的属性,如年龄/姓名/体重。

此外,子类(具有“Pet”作为“父实体”的实体,如“Dog”和“Cat”)除了“Pet”的属性外,还可以拥有自己的属性,就像“Dog”有一个“barkSound”和“Cat”有一个“meowSound”。

您当然可以根据需要在存储中添加任意数量的人,这与数据模型无关。

要检索信息,只需使用获取请求即可获取所有人员。然后循环访问他们的“宠物”属性,为他们的宠物获取NSSets。您可以循环访问这些集以访问宠物的信息。

这是一个如何获取所有人,然后是所有宠物的例子:

// Fetch all persons
NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];
NSEntityDescription *entity = [NSEntityDescription entityForName:@"Person" inManagedObjectContext:yourContext];
[fetchRequest setEntity:entity];

NSError *error = nil;
NSArray *fetchedObjects = [yourContext executeFetchRequest:fetchRequest error:&error];
if (fetchedObjects == nil) {
    // Handle error case
}

[fetchRequest release];

// Loop through all their pets
for (Person* person in fetchedObjects)
{
    NSLog(@"Hello, my name is %@", person.name);

    for (Pet* pet in person.pets) {
        if ([pet isKindOfClass:[Dog class]])
        {
            NSLog(@"Woof, I'm %@, owned by %@", pet.name, pet.owner.name);
        }
        else
        {
            NSLog(@"Meow, I'm %@, owned by %@", pet.name, pet.owner.name);
        }
    }
}

请注意,您也可以在不通过其所有者的情况下获取宠物:

// Fetch all persons
NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];
NSEntityDescription *entity = [NSEntityDescription entityForName:@"Pet" inManagedObjectContext:yourContext];
[fetchRequest setEntity:entity];
[fetchRequest setIncludesSubentities:YES]; // State that you want Cats and Dogs, not just Pets.

NSError *error = nil;
NSArray *fetchedObjects = [yourContext executeFetchRequest:fetchRequest error:&error];
if (fetchedObjects == nil) {
    // Handle error case
}

[fetchRequest release];

上面的代码未经过测试,可能包含拼写错误,但会告诉您如何操作。