gpt4 book ai didi

ios - 核心数据 : How to get data of entity in relationship?

转载 作者:行者123 更新时间:2023-11-29 02:26:55 26 4
gpt4 key购买 nike

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

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

最佳答案

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

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

如果你需要地址,你可以用

NSSet *addresses = person.addresses;

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

顺便说一句,您设置关系的方式不必要地复杂并且容易出错。如果关系的一侧是一对一的,则使用它来定义关系:

newAddress.person = person; 

关于ios - 核心数据 : How to get data of entity in relationship?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27403451/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com