在UITableView中获取Core Data对象的indexPath

Ken*_*ent 4 core-data uitableview nsindexpath nsfetchedresultscontroller ios

我有一个UITableView,我使用以下NSfetchedResultsController从Core Data填充:

- (NSFetchedResultsController *)fetchedResultsController {
    if (_fetchedResultsController != nil) {
        return _fetchedResultsController;
    }

    NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];
    NSEntityDescription *entity = [NSEntityDescription entityForName:@"Event" inManagedObjectContext:_managedObjectContext];
    [fetchRequest setEntity:entity];

    NSSortDescriptor *sort = [[NSSortDescriptor alloc] initWithKey:@"date" ascending:YES];
    [fetchRequest setSortDescriptors:[NSArray arrayWithObject:sort]];

    [fetchRequest setFetchBatchSize:20];

    NSFetchedResultsController *theFetchedResultsController = [[NSFetchedResultsController alloc] initWithFetchRequest:fetchRequest managedObjectContext:_managedObjectContext sectionNameKeyPath:nil cacheName:@"Root"];
    self.fetchedResultsController = theFetchedResultsController;
    _fetchedResultsController.delegate = self;

    return _fetchedResultsController;
}
Run Code Online (Sandbox Code Playgroud)

我有另一个方法附加到"添加"按钮,该按钮将新的核心数据项添加到数据库.添加对象后,我的表会正确更新,并且根据获取的结果控制器中的"日期"排序,新对象将显示在正确的位置.我的新对象使用今天的日期添加其"日期"属性.我添加这样的对象:

NSManagedObject *newEvent = [NSEntityDescription insertNewObjectForEntityForName:@"Event" inManagedObjectContext:context];
[newEvent setValue:@"New Client" forKey:@"name"];
[newEvent setValue:[NSDate date] forKey:@"date"];
NSError *error;
    if (![context save:&error]) {
        NSLog(@"Core Data error!  Could not save: %@", [error localizedDescription]);
    }
Run Code Online (Sandbox Code Playgroud)

现在,作为我的"添加"方法的一部分,我需要选择添加新项目的行并转到编辑屏幕.显然,根据表中项目的其他日期,它可能在任何地方.

我想像这样选择它,但我没有indexPath:

[self.eventListTable selectRowAtIndexPath:indexPath animated:YES  scrollPosition:UITableViewScrollPositionBottom];
Run Code Online (Sandbox Code Playgroud)

如何确定添加新对象的行(indexPath)以便我可以正确选择它?

谢谢!

Dan*_*lly 12

NSFetchedResultsController 有一个方法叫: indexPathForObject:

如果在更改处理期间插入了项目(FRC委托方法),请选择最近插入的项目.您可以使用上述方法确定对象的索引路径.

或者,您可以保留最后一次插入的插入对象,并在didChangeContent委托方法中,选择插入的项目并使您保留的变量无效(因此更多的calles不会触发segue).