开发者

Core Data: Automatically select next table row when record deleted

开发者 https://www.devze.com 2023-03-31 16:43 出处:网络
I\'m working on a Core Data driven开发者_如何学运维 iPad app with a split view controller. Just imagine the iPad Mail app and you\'ll be on the right track. When I select a record in the Root View Con

I'm working on a Core Data driven开发者_如何学运维 iPad app with a split view controller. Just imagine the iPad Mail app and you'll be on the right track. When I select a record in the Root View Controller, the details display in the DetailViewController.

On the Detail View, I have a delete button. When clicked, it tells its Core Data context to delete the current object. It performs the delete correctly and the row disappears from the RootViewController, as it should.

How can I get the RootViewController to automatically select the row after the row that was deleted so it subsequently displays the details in the detail view? (Or automatically select the previous row if the deleted row was the last row?)


If you use an NSFetchedResultsController to manage the table then you can use it's delegate methods to respond to changes.

Use the controller:didChangeObject:atIndexPath:forChangeType:newIndexPath: delegate method and check for the NSFetchedResultsChangeDelete change type.

You can see if the indexPath matches the currently selected rows in your table and then act upon that.


OK. I think I figured it out. Here's what I did. (Please chime in if you see a better way.)

First, I defined a new NSInteger ivar, lastSelectedRow.

Next, I changed

   case NSFetchedResultsChangeDelete: {
       [tableView deleteRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationFade];
       break;

to

   case NSFetchedResultsChangeDelete: {
       [tableView deleteRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationFade];
       lastSelectedRow = indexPath.row;
       id <NSFetchedResultsSectionInfo> sectionInfo = [[self.fetchedResultsController sections] objectAtIndex:0];
       if (lastSelectedRow == [sectionInfo numberOfObjects]) {
           --lastSelectedRow;
       }
       break;
   }

Then I changed

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

to

- (void)controllerDidChangeContent:(NSFetchedResultsController *)controller
{
    [self.tableView endUpdates];
    if (lastSelectedRow > -1) {
        NSIndexPath *newIndexPath = [NSIndexPath indexPathForRow:lastSelectedRow inSection:0];
        [self.tableView selectRowAtIndexPath:newIndexPath animated:YES scrollPosition:UITableViewScrollPositionNone];
        [self tableView:self.tableView didSelectRowAtIndexPath:newIndexPath];
        lastSelectedRow = -1;
    }
}

Und voila!!

As an added bonus I can now store the last selected row when my app is terminated, and I can go right back to it next time it launches.

0

精彩评论

暂无评论...
验证码 换一张
取 消