iPhone核心数据关系

Vik*_*ngs 5 iphone xcode core-data ios

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

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

(2)也可能有多个人.

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

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

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

在此输入图像描述

Jia*_*Yow 11

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

在此输入图像描述

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

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

此外,子类(实体具有"宠物"和"父实体",如"狗"和"猫"),可以在除了"宠物",属性像"狗"自己的属性有一个"barkSound" ,"猫"有一个"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);
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

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

// 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];
Run Code Online (Sandbox Code Playgroud)

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