I have a UITableView that I'm populating from Core Data with the following NSfetchedResultsController:
- (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;
}
I have another method attached to an "Add" button that adds a new Core Data item to database. As soon as the object is added, my table updates properly and the new object is shown in its correct spot according to the "date" sort in the fetched results controller. My new object is added using today's date for its "date" attribute. I add the object like this:
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]);
}
Now, as part of my "Add" method, I need to select the row where the new item was added and segue to an edit screen. Obviously, depending on the other dates of items in the table, it could be anywhere.
I want to select it like this, but I don't have the indexPath:
[self.eventListTable selectRowAtIndexPath:indexPath animated:YES scrollPosition:UITableViewScrollPositionBottom];
How do I determine which row (indexPath) my new object was added at so that I can select it properly?
Thanks!
NSFetchedResultsController
have a method called: indexPathForObject:
If you have inserted items during your change processing (the FRC delegate methods), select the most recent inserted item. you can determine the index path of the object using the method above.
Or, you could keep the inserted object from your last insert, and in the didChangeContent
delegate method, select the inserted item and nullify the variable you kept (so further calles won't trigger the segue).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With