我在创建和理解如何为这种情况创建核心数据模型时遇到问题。
(1) 一个人可以养多只宠物(狗或猫的组合)。
(2) 也可以多人。
我想遍历 Person 实体并提取每个人、每只宠物和那里的信息。
我不确定是否应该使用关系,或者如何在 Core Data 中设置此模型。我迅速记下了我认为模型的外观的选择器。为了简单起见,我制作了这个模型,我的模型不处理猫狗。
非常感谢任何建议或想法。
最佳答案
我很快为你组装了一个模型:
所以,基本上“人”就是你的人,它与“宠物”有关系——这是一种“对多”关系。一个人可以养多只宠物。
然后有一个“宠物”实体。它是代表任何宠物、猫和狗的抽象实体。与“人”的“宠物”成反比关系。因此,从任何一只宠物身上,你总能追溯到对应的主人。此外,“Pet”的每个子类都有一些共同的属性,如年龄/姓名/体重。
此外,子类(以“Pet”为“父实体”的实体,如“Dog”和“Cat”)除了“Pet”的属性外还可以有自己的属性,如“Dog”有一个“barkSound”,而“Cat”有“meowSound”。
当然,你可以根据需要将任意数量的人添加到你的存储中,这与数据模型无关。
要检索信息,只需使用提取请求来提取所有人员。然后遍历它们并访问它们的“宠物”属性以获得宠物的 NSSet。您可以循环访问这些集合以访问宠物的信息。
这里是一个例子,说明如何获取所有的人,然后是所有的宠物:
// 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];
上面的代码未经测试,可能包含拼写错误,但会告诉您如何做。
关于iPhone核心数据关系,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9627140/