将 HBSFetchedTableController 目录添加到您的项目中。
HBSFetchedTableController 与 4 个对象一起工作
#import "HBSFetchedTableController.h"
self.fetchedTableViewController = [[HBSFetchedTableController alloc] initWithTableView:self.tableView
fetchedResultController:self.fetchedResultsController
delegate:self
andTableViewFactory:self.tableViewFactory];
创建一个 UIViewController 子类,使其符合 HBSFetchedTableControllerDelegate,并将所有需要 (如 tableView:didSelectRowAtIndexPath:
)的 UITableViewDelegate 用户事件方法放入其中。创建一个符合 HBSTableViewFactory 协议的类,并将所有单元格配置方法放入其中。现在,您只需配置 NSFetchedResultController。有了 tableView、代理、工厂和 fetched controller,您可以通过 initWithTableView:delegate:andTableViewFactory:
(或简单的 init
并逐个传递代理和工厂)创建 HBSFetchedTableController。这就是全部!您的表格已填充了检索到的结果。
示例项目是一个简单的“笔记本”应用程序,该应用程序使用 CoreData 存储数据。示例显示了工厂、代理、CoreData 堆栈、配置检索结果控制器以及按部分获取对象的使用情况。主要逻辑隐藏在 'abstract' HBSFetchedTableViewController 类中。打开它,转到 viewDidLoad 方法。HBSNotebooksViewController 和 HBSNotesViewController 从它继承,并重写了获取配置方法。
要运行示例项目,请克隆仓库,然后从示例目录运行pod install
。
HBSFetchedTableController将其本身设置为tableView的委托,以接收行配置调用并将其转发到工厂。如果您需要tableView的方法,只需在viewController(或其他对象)中实现该方法,并将其设置为fetchedTableController.delegate。如果委托响应这些方法,则FetchedTableController将大多数重要方法转发到委托。FetchedTableController有一个字符串数组(属性delegateSelectorsToForward
),表示选择器签名,因此如果您需要一些额外的方法,只需将签名添加到数组中。此属性是默认数组,而非默认数组的附加,因此请勿忘记将默认数组包含到您的新数组中。默认转发的方法定义如下:
- tableView:shouldHighlightRowAtIndexPath:
- tableView:didSelectRowAtIndexPath:
- tableView:didDeselectRowAtIndexPath:
- tableView:commitEditingStyle:forRowAtIndexPath:
- tableView:canEditRowAtIndexPath:
- tableView:canMoveRowAtIndexPath:
- tableView:moveRowAtIndexPath:toIndexPath:
- tableView:accessoryButtonTappedForRowWithIndexPath:
将tableView的行为方法与配置方法分离是一种很好的做法。大多数方法签名与UITableViewDelegate和DataSource签名重复,但提供NSString作为节名称而不是仅索引(没有转换则无用)。
工厂实现了两个必需的方法
- tableView:cellForRowAtIndexPath:withObject:inSection:
- configureCell:atIndexPath:withObject:inSection:
第一个方法在tableView即将显示cell之前调用。在该方法中,工厂只需要创建(或deque)cell并返回它。第二个方法在第一个方法之后调用,在其他情况下 - 当fetchedResultsController表示对象已更改或移动时。在这里,工厂执行所有cell配置。
安诺科夫·帕威尔,请发邮件至[email protected]
HBSFetchedTableController受MIT许可的约束。有关更多信息,请参阅LICENSE文件。