要与 Core Data 集成,您只需要将TLCollapsibleTableViewController's
default替换TLIndexPathController
为初始化为NSFetchRequest
:
- (void)viewDidLoad
{
[super viewDidLoad];
// replace default indexPathController with one configured with an NSFetchRequest
NSManagedObjectContext *context = ...;// Your managed object context
NSFetchRequest *fetch = ...; // Request that fetches Scales sorted by category
self.indexPathController = [[TLIndexPathController alloc] initWithFetchRequest:fetch managedObjectContext:context sectionNameKeyPath:@"categories" identifierKeyPath:nil cacheName:nil];
// perform initial fetch
NSError *error;
[self.indexPathController performFetch:error];
if (error) {
// handle error
}
}
这个答案的其余部分解释了核心数据集成是如何工作的,并强调了TLIndexPathControllerDelegate
.
TLCollapsibleTableViewController
用作TLCollapsibleDataModels
数据模型。TLCollapsibleDataModels
通过提供一个包含所有可能行和一组扩展部分名称的支持数据模型来构建:
TLCollapsibleDataModel *dataModel = [[TLCollapsibleDataModel alloc] initWithBackingDataModel:backingDataModel expandedSectionNames:expandedSectionNames];
生成的数据模型仅包含要显示的行(尽管可以通过backingDataModel
属性访问完整的数据集)。所做的是TLCollapsibleTableViewController
在用户展开或折叠部分时自动更新数据模型。
当您如上所述启用 Core Data 集成时,TLIndexPathController
还将在初始获取结果和任何获取结果更改时自动更新数据模型。但是这个数据模型是后备模型,需要转换为TLCollapsibleDataModel
. 为了自动实现这一点,我添加了以下实现controller:willUpdateDataModel:withDataModel:
,它允许在生成更新之前任意修改新数据模型:
- (TLIndexPathDataModel *)controller:(TLIndexPathController *)controller willUpdateDataModel:(TLIndexPathDataModel *)oldDataModel withDataModel:(TLIndexPathDataModel *)updatedDataModel
{
// If `updatedDataModel` is already a `TLCollapsibleDataModel`, we don't need to do anything.
if ([updatedDataModel isKindOfClass:[TLCollapsibleDataModel class]]) {
return nil;
}
// Otherwise, we assume `updatedDataModel` is the backing model - maybe it came from a
// Core Data fetch request or maybe it was provided by custom code - and we need to
// constructe the `TLCollapsibleDataModel`.
NSMutableSet *expandedSectionNames = nil;
// If `oldDataModel` is a `TLCollapsibleDataModel`, we need to preserve the
// expanded state of known sections.
if ([oldDataModel isKindOfClass:[TLCollapsibleDataModel class]]) {
expandedSectionNames = [NSMutableSet setWithSet:((TLCollapsibleDataModel *)oldDataModel).expandedSectionNames];
// Now filter out any section names that are no longer present in `updatedDataModel`
[expandedSectionNames intersectSet:[NSSet setWithArray:updatedDataModel.sectionNames]];
}
// Construct and return the `TLCollapsibleDataModel`
TLCollapsibleDataModel *dataModel = [[TLCollapsibleDataModel alloc] initWithBackingDataModel:updatedDataModel expandedSectionNames:expandedSectionNames];
return dataModel;
}
因此,如果updatedDataModel
不是 a TLCollapsibleDataModel
,则假定它是支持模型并转换为TLCollapsibleDataModel
,保留在 中捕获的展开状态oldDataModel
。这不仅适用于NSFetchRequest
生成的更新,而且您还可以在自定义代码中设置支持模型,self.indexPathController.items = ...
或者self.indexPathController.dataModel = ...
如果您有任何理由这样做。