sectionNameKeyPath
是只读的。因此,一种方法是在视图控制器上设置一个布尔搜索状态,如果您正在搜索,则该状态 == YES。然后 ...
// assuming ARC
- (void)setSearch:(BOOL)search {
if (_search == search) return;
_search = search;
self.fetchedResultsController = nil;
}
这将导致您的 FRC 延迟初始化在下次请求时发生...
- (NSFetchedResultsController *)fetchedResultsController {
if (_fetchedResultsController != nil) {
return _fetchedResultsController;
}
// here's the key - set this based on search state
NSString *sectionNameKeyPath = (self.search)? nil : @"mySectionNameKeyPath";
_fetchedResultsController =
[[NSFetchedResultsController alloc] initWithFetchRequest:fetchRequest
managedObjectContext:moc
sectionNameKeyPath:sectionNameKeyPath
cacheName:@"Root"];
// and so on
}
感觉像是浪费查询来更改搜索模式,但希望这不会太昂贵。