核心数据:如何获取关系中的实体数据?

时间:2014-12-10 14:25:27

标签: ios core-data fetch

我在数据库中有一些数据。有一个人和他的地址作为一对多的关系,保存如下:

// 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);
}

1 个答案:

答案 0 :(得分:1)

只需抓取Person即可。一旦需要属性,将以优化的方式为您完成获取属性。您只需访问属性(假设它们已经存在)。

NSString *message = [NSString stringWithFormat:@"Hello, %@.", person.first];

如果您需要地址,可以使用

NSSet *addresses = person.addresses;

它们没有特定的顺序,但您可以使用sortedArrayUsingDescriptors和类似的方法对它们进行排序。在任何情况下,您都不需要其他获取请求。

BTW,您设置关系的方式不必要地复杂且容易出错。如果关系的一方是一对,用它来定义关系:

newAddress.person = person;