【发布时间】:2013-08-23 08:09:28
【问题描述】:
对于 EntityA 与 EntityB 具有多对一关系的核心数据模型,我想创建一个 EntityA 对象列表,按与之相关的 EntityB 的名称排序。通常要做到这一点,我会像这样设置获取请求:
if (_fetchedResultsController != nil) {
return _fetchedResultsController;
}
NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];
然后我会设置我的请求值:(在这种情况下,它是按物种名称排序的植物列表。有些植物没有设置物种。)
NSEntityDescription *entity = [NSEntityDescription entityForName:@"Plant" inManagedObjectContext:self.managedObjectContext];
NSSortDescriptor *sortDescriptorOne = [[NSSortDescriptor alloc] initWithKey:@"species.name" ascending:YES];
NSString *sectionKeyPath = @"species.name";
然后我用通常的东西完成它:
[fetchRequest setEntity:entity];
// Set the batch size to a suitable number.
[fetchRequest setFetchBatchSize:20];
NSArray *sortDescriptors = @[sortDescriptorOne];
[fetchRequest setSortDescriptors:sortDescriptors];
NSFetchedResultsController *aFetchedResultsController = [[NSFetchedResultsController alloc] initWithFetchRequest:fetchRequest
managedObjectContext:self.managedObjectContext
sectionNameKeyPath:sectionKeyPath
cacheName:@"plantsCache"];
aFetchedResultsController.delegate = self;
self.fetchedResultsController = aFetchedResultsController;
[NSFetchedResultsController deleteCacheWithName:@"plantsCache"];
NSError *error = nil;
if (![self.fetchedResultsController performFetch:&error]) {
NSLog(@"Unresolved error %@, %@", error, [error userInfo]);
abort();
}
return _fetchedResultsController;
但是我得到的结果对我不起作用,因为这种关系是可选的。所以有些EntityA与EntityB有关系,有些则没有。当EntityA的relationship的值为nil时,结果控制器似乎不知道该怎么做。
任何建议我可以做些什么来继续使用关系的值制作部分但允许某些对象具有 nil ?
【问题讨论】:
-
EntityA 是植物,EntityB 是物种?那么一对多的关系是从 EntityB 到 EntityA,而不是像你的第一句话那样相反? - 与物种无关的植物实际上会发生什么?它们没有被提取,没有显示,......?
-
你说得对,我把它弄反了。我的意思是EntityA(植物)与EntityB(物种)具有多对一的关系。与任何物种无关的植物出现在空白(未命名)部分,核心数据向控制台抱怨。这种行为实际上是我想要的。但是,如果我从详细视图返回到列表视图,添加了一个没有物种的植物,列表将不会显示额外的植物项目,直到再次调用 fetchedresultscontroller。理想情况下,我不想在 viewWillAppear 上重新填充结果控件。
-
未命名部分问题(和投诉)也许可以通过将方法(或瞬态属性)
sectionName添加到 Plant 实体并将其用作sectionNameKeyPath来解决。该方法应返回self.species.name或空字符串。 - 我目前无法对此进行测试,所以我不知道这是否真的有帮助。 -
谢谢!我会试试的。
标签: iphone ios objective-c cocoa core-data