我在数据库中有一些数据。有一个人和他的地址作为一对多的关系,保存如下:
// 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);
}
现在我需要取这个人。我可以获取他的所有属性,但我应该如何获得他们的地址和属性呢?
到目前为止我的代码:
// 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);
}
答案 0 :(得分:1)
只需抓取Person
即可。一旦需要属性,将以优化的方式为您完成获取属性。您只需访问属性(假设它们已经存在)。
NSString *message = [NSString stringWithFormat:@"Hello, %@.", person.first];
如果您需要地址,可以使用
NSSet *addresses = person.addresses;
它们没有特定的顺序,但您可以使用sortedArrayUsingDescriptors
和类似的方法对它们进行排序。在任何情况下,您都不需要其他获取请求。
newAddress.person = person;