Related data

I am having problems creating and understanding how to create a basic data model for this situation.

(1) A person may have several pets (or a combination of dog or cat).

(2) There may also be several people.

I want to go through the essence of Person and pull out every person, as well as every pet and there information.

I'm not sure if I should use relationships or how to install this model in Core Data. I quickly recorded a collector of what I thought would look like a model. I made this model for simplicity, my model does not apply to cats and dogs.

Any suggestions or ideas are welcome.

enter image description here

+5
source share
1 answer

I quickly put together a model for you:

enter image description here

, "" - , " " - " ". .

"Pet". , , . " " "". . , "Pet" , //.

, (, "Pet" " ", "" "" ) "Pet", , "" "barkSound", "Cat" "meowSound".

, , , .

, . " ", NSS . .

, , :

// 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];

, , .

+11

All Articles