0

我对核心数据有疑问。我读到 Core Data 懒得加载实体关系,以防万一,它没有一对多关系。

我有一个实体“项目”,它与一个实体“运动”有关系(多对多关系)。 在此处输入图像描述

在这个方法中,除了加载“Movement”的所有实例之外,我还想加载“Item”的相关属性,例如“name”。

//Core data request
NSError *error;
NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];
NSEntityDescription *entity = [NSEntityDescription entityForName:@"Movement"
                                          inManagedObjectContext:self.managedObjectContext];
[fetchRequest setEntity:entity];
fetchRequest.sortDescriptors = [NSArray arrayWithObject:[NSSortDescriptor sortDescriptorWithKey:@"date" ascending:YES selector:@selector(localizedCaseInsensitiveCompare:)]];

NSFetchedResultsController *result = [[NSFetchedResultsController alloc] initWithFetchRequest:fetchRequest
                                                                         managedObjectContext:self.managedObjectContext sectionNameKeyPath:nil
                                                                                    cacheName:@"Root"];

[result performFetch: &error];

为了看看它是否有效,我添加了这段代码:

NSArray *array = [NSArray arrayWithArray:[self.managedObjectContext executeFetchRequest:fetchRequest error:&error]];
for (int i = 0; i < array.count; i++) {
    Movement *movement = [array objectAtIndex:i]
    NSLog(@"item name %@",movement.movement_inItem.name);
}

结果为 null项目名称 (null)

我环顾四周,试图把这段代码放在[fetchRequest setEntity:entity];

NSString *relationshipKeyPath = @"movement_inItem";
NSArray *keyPaths = [NSArray arrayWithObject:relationshipKeyPath];
[fetchRequest setRelationshipKeyPathsForPrefetching:keyPaths];
[fetchRequest setIncludesSubentities:YES];

但没有任何改变。

非常感谢!

4

0 回答 0