我有一个 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;
}
我有另一种方法附加到“添加”按钮,用于将新的核心数据项添加到数据库。一旦添加了对象,我的表就会正确更新,并且新对象会根据获取结果 Controller 中的“日期”排序显示在正确的位置。我的新对象是使用今天的日期作为其“日期”属性添加的。我这样添加对象:
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]);
}
现在,作为我的“添加”方法的一部分,我需要选择添加新项目的行并转至编辑屏幕。显然,根据表中项目的其他日期,它可能在任何地方。
我想这样选择它,但是我没有indexPath:
[self.eventListTable selectRowAtIndexPath:indexPath animated:YES scrollPosition:UITableViewScrollPositionBottom];
如何确定我的新对象添加到哪一行 (indexPath),以便我可以正确选择它?
谢谢!
最佳答案
NSFetchedResultsController
有一个方法叫做:indexPathForObject:
如果您在更改处理(FRC 委托(delegate)方法)期间插入了项目,请选择最近插入的项目。您可以使用上述方法确定对象的索引路径。
或者,您可以保留上次插入的插入对象,并在 didChangeContent
委托(delegate)方法中,选择插入的项目并使您保留的变量无效(因此进一步的调用不会触发 segue ).
关于ios - 获取 UITableView 中 Core Data 对象的 indexPath,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22292079/