I have some data in Database. There's a Person and his Addresses as One-to-Many relationship, saved like this:
// Create Person
NSEntityDescription *entityPerson = [NSEntityDescription entityForName:@"Person" inManagedObjectContext:self.managedObjectContext];
NSManagedObject *newPerson = [[NSManagedObject alloc] initWithEntity:entityPerson insertIntoManagedObjectContext:self.managedObjectContext];
// Set First and Last Name
[newPerson setValue:@"Bart" forKey:@"first"];
[newPerson setValue:@"Jacobs" forKey:@"last"];
[newPerson setValue:@44 forKey:@"age"];
// Create Address
NSEntityDescription *entityAddress = [NSEntityDescription entityForName:@"Address" inManagedObjectContext:self.managedObjectContext];
NSManagedObject *newAddress = [[NSManagedObject alloc] initWithEntity:entityAddress insertIntoManagedObjectContext:self.managedObjectContext];
// Set info
[newAddress setValue:@"Main Street" forKey:@"street"];
[newAddress setValue:@"Boston" forKey:@"city"];
// Add Address to Person
[newPerson setValue:[NSSet setWithObject:newAddress] forKey:@"addresses"];
// Create Address
NSManagedObject *otherAddress = [[NSManagedObject alloc] initWithEntity:entityAddress insertIntoManagedObjectContext:self.managedObjectContext];
// Set info
[otherAddress setValue:@"5th Avenue" forKey:@"street"];
[otherAddress setValue:@"New York" forKey:@"city"];
// Add Address to Person
NSMutableSet *addresses = [newPerson mutableSetValueForKey:@"addresses"];
[addresses addObject:otherAddress];
// Save Managed Object Context
NSError *error = nil;
if (![newPerson.managedObjectContext save:&error]) {
NSLog(@"Unable to save managed object context.");
NSLog(@"%@, %@", error, error.localizedDescription);
}
Now I need to fetch this person. I can fetch all of his attributes, but how should I get his addresses and attributes of them?
My code so far:
// Fetching
NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] initWithEntityName:@"Person"];
// Execute Fetch Request
NSError *fetchError = nil;
NSArray *result = [self.managedObjectContext executeFetchRequest:fetchRequest error:&fetchError];
if (!fetchError) {
for (NSManagedObject *managedObject in result) {
NSLog(@"%@, %@", [managedObject valueForKey:@"first"], [managedObject valueForKey:@"last"]);
// HERE I WANT TO PRINT INFO ABOUT HIS ADDRESSES
}
} else {
NSLog(@"Error fetching data.");
NSLog(@"%@, %@", fetchError, fetchError.localizedDescription);
}