消除了与NSFetchedResultsController和UITableView相关的模板代码。
典型用法
@interface MyViewController () <CoreDataTableViewDelegate>
@property (nonatomic, weak) IBOutlet CoreDataTableView *tableView;
@property (nonatomic, strong) NSManagedObjectContext *managedObjectContext;
@end
@implementation MyViewController
- (void)viewDidLoad
{
NSFetchRequest *fetchRequest = [NSFetchRequest fetchRequestWithEntityName:@"Person"];
NSSortDescriptor *lastName = [NSSortDescriptor sortDescriptorWithKey:@"lastName" ascending:YES];
NSSortDescriptor *firstName = [NSSortDescriptor sortDescriptorWithKey:@"firstName" ascending:YES];
[fetchRequest setSortDescriptors:@[lastName, firstName]];
NSFetchedResultsController *frc = [[NSFetchedResultsController alloc] initWithFetchRequest:fetchRequest managedObjectContext:self.managedObjectContext sectionNameKeyPath:@"age" cacheName:nil];
self.tableView.fetchedResultsController = frc;
self.tableView.coreDataTableViewDelegate = self;
}
- (void)configureCell:(UITableViewCell *)cell withObject:(NSManagedObject *)object forTableView:(CoreDataTableView *)tableView
{
NSString *firstName = [object valueForKey:@"lastName"];
NSString *lastName = [object valueForKey:@"firstName"];
cell.textLabel.text = [NSString stringWithFormat:@"%@ %@", firstName, lastName];
}
用户可以通过滑动来删除单元格——删除单元格及其在Core Data中的备份对象。
self.tableView.swipeToDelete = YES;
在左上角显示一个编辑按钮,可以切换编辑的开和关。
self.tableView.editable = YES;
在右上角显示一个加号按钮,它创建一个新的NSManagedObject并调用代理方法。
self.tableView.addButton = YES;
- (void)configureNewObject:(NSManagedObject *)object forTableView:(CoreDataTableView *)tableView
{
NSLog(@"New object: %@. Yay!", object);
}
在编辑模式下允许用户重新排列单元格。
self.tableView.reOrderable = YES;
- (void)tableView:(CoreDataTableView *)tableView didReOrderObject:(NSManagedObject *)object atIndexPath:(NSIndexPath*)sourceIndexPath toIndexPath:(NSIndexPath *)newIndexPath
{
object.order = newIndexPath.row; //Simplified, but you get the idea.
}
增加一个搜索栏来通过表格视图进行搜索。实现搜索预测代理方法。
self.tableView.searchBar = YES;
- (NSPredicate *)predicateForString:(NSString *)searchString inTableView:(CoreDataTableView *)tableView;//Return a predicate for the given searchString
{
NSPredicate *searchPredicate = [NSPredicate predicateWithFormat:@"SELF.searchString contains[cd] %@", searchString];
return searchPredicate;
}
自解释的方法
- (void)accessoryButtonTappedForRowWithIndexPath:(NSIndexPath *)indexPath inTableView:(CoreDataTableView *)tableView;
- (void)tableView:(CoreDataTableView *)tableView didSelectObject:(NSManagedObject *)object atIndexPath:(NSIndexPath *)indexPath;
- (BOOL)tableView:(CoreDataTableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath;
- (BOOL)tableView:(CoreDataTableView *)tableView canMoveRowAtIndexPath:(NSIndexPath *)indexPath;
- (BOOL)tableView:(CoreDataTableView *)tableView shouldMoveRowAtIndexPath:(NSIndexPath *)sourceIndexPath toIndexPath:(NSIndexPath *)proposedDestinationIndexPath;