代码之家  ›  专栏  ›  技术社区  ›  rustyshelf

带索引的核心数据备份UITableView

  •  8
  • rustyshelf  · 技术社区  · 16 年前

    我正在尝试实现一个支持索引的核心数据备份UITableView(例如:显示在下面的字符以及与之配套的节标题)。在没有核心数据的情况下,我完全可以使用:

    - (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section;
    - (NSArray *)sectionIndexTitlesForTableView:(UITableView *)tableView;
    

    我还可以在不使用索引的情况下实现由核心数据支持的UITableView。

    我想知道的是如何将两者优雅地结合起来?显然,一旦对内容进行索引和重新分区,就不能再使用标准的NSFetchedResultsController在给定的索引路径上检索内容。因此,我将索引字母存储在NSArray中,将索引内容存储在NSDictionary中。这一切都可以很好地用于显示,但在添加和删除行时,我遇到了一些真正的难题,特别是如何正确地实现这些方法:

    - (void)controllerWillChangeContent:(NSFetchedResultsController *)controller;
    
    - (void)controller:(NSFetchedResultsController *)controller didChangeObject:(id)anObject atIndexPath:(NSIndexPath *)indexPath forChangeType:(NSFetchedResultsChangeType)type newIndexPath:(NSIndexPath *)newIndexPath;
    
    - (void)controller:(NSFetchedResultsController *)controller didChangeSection:(id <NSFetchedResultsSectionInfo>)sectionInfo atIndex:(NSUInteger)sectionIndex forChangeType:(NSFetchedResultsChangeType)type;
    
    - (void)controllerDidChangeContent:(NSFetchedResultsController *)controller;
    

    因为它返回给我的索引路径与核心数据中的路径没有关联。当用户添加一行时,我只需重建我的索引NSArray和NSDictionary,而当用户删除一行时,我也会重建索引NSArray和NSDictionary,这样做会使整个应用程序崩溃。

    编辑:我只是想澄清一下,我知道NSFetchedResultsController是开箱即用的,但我想复制的是像Contacts应用程序这样的功能,其中索引是人名的第一个字母。

    1 回复  |  直到 16 年前
        1
  •  21
  •   Community Mohan Dere    9 年前

    您应该使用CoreData NSFetchedResultsController获取节/索引。

    NSSortDescriptor *sortDescriptor = [[NSSortDescriptor alloc]
    initWithKey:@"name" // this key defines the sort
    ascending:YES];
    NSArray *sortDescriptors = [[NSArray alloc] initWithObjects:sortDescriptor, nil];
    [fetchRequest setSortDescriptors:sortDescriptors];
    
    NSFetchedResultsController *aFetchedResultsController = [[NSFetchedResultsController alloc] initWithFetchRequest:fetchRequest managedObjectContext:managedObjectContext
    sectionNameKeyPath:@"name" // this key defines the sections
    cacheName:@"Root"];
    aFetchedResultsController.delegate = self;
    self.fetchedResultsController = aFetchedResultsController;
    

    然后,您可以获得如下节名:

    - (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section {
        id <NSFetchedResultsSectionInfo> sectionInfo = [[fetchedResultsController sections] objectAtIndex:section];
        return [sectionInfo name];
    }
    

    节索引如下所示:

    id <NSFetchedResultsSectionInfo> sectionInfo = [[fetchedResultsController sections] objectAtIndex:section];
    [sectionInfo indexTitle]; // this is the index
    

    对内容的更改仅表明需要更新表:

    - (void)controllerDidChangeContent:(NSFetchedResultsController *)controller {
        [self.tableView reloadData];
    }
    


    这只适用于索引和快速索引滚动,不适用于节标题。
    看见 this answer

    推荐文章