我的核心数据存在问题。我读到Core Data懒得加载实体关系,如果这样,就没有多对多的关系。
我有一个实体“Item”,它与实体“Movement”有一个关系(to-many关系)。
在这个方法中,除了加载“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];
但没有任何改变。
非常感谢!