0

I cannot seem to find a way to detect when a user presses the back button in a UINavigationController. I have tried using the UINavigationControllerDelegate

- (void)navigationController:(UINavigationController *)navigationController willShowViewController:(UIViewController *)viewController animated:(BOOL)animated

I have tried

- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];

    if (self.isMovingFromParentViewController) {
        NSLog(@"BACK BUTTON WAS PRESSED!!!!!!!!!");
        [[[NSManagedObjectContext MR_defaultContext] undoManager] endUndoGrouping];
        [[NSManagedObjectContext MR_defaultContext] undo];
    }

}

and I have also tried

 - (void)viewDidLoad
 {
    self.navigationItem.backBarButtonItem.target = self;
    self.navigationItem.backBarButtonItem.action = @selector(cancelPressed);
 }

- (void)cancelPressed
{
    NSLog(@"CANCEL BUTTON WAS PRESSED!!!!!!!!!");
    [[[NSManagedObjectContext MR_defaultContext] undoManager] endUndoGrouping];
    [[NSManagedObjectContext MR_defaultContext] undo];
}

The first 2 work great however, when I press Done I run an AFNetworking call then onComplete of that I do a [[NSNotificationCenter defaultCenter] postNotificationName:] and then the parentViewController runs a few things and refreshes the screen and pops the child view controller. Upon this child view controller popping, the first 2 also run.

The last one I mentioned doesn't work at all. Is there a proper way to check if the back button of a navigationController was pressed that will run for the back button only and not just when the view controller is popped?

Bot
  • 11,868
  • 11
  • 75
  • 131
  • You can do this with a custom UIBarButtonItem, but I don't think what you're describing is possible with the stock UINavigationController back button. – Matt Logan Oct 07 '13 at 22:47

2 Answers2

0

I would implement an unwind segue, What are Unwind segues for and how do you use them?

You can then implement the below method on your parent viewController which is called when the user presses "Done"

  - (IBAction)unwindToParent:(UIStoryboardSegue *)unwindSegue
Community
  • 1
  • 1
Kyle C
  • 4,077
  • 2
  • 31
  • 34
  • This will still cause the `viewWillDisappear` to run which would still run the undo manager. – Bot Oct 07 '13 at 23:09
0

I came about this with a different approach. My overall goal was to unset changed core data items that were changed but then the back button was pressed. Instead I created a new context for the editing. If the save button was pressed the new context would be merged into the main context. If the back button was pressed the new context would simply go away and so would the changes.

Bot
  • 11,868
  • 11
  • 75
  • 131