2
votes

I have a stack of UIViewController subclasses. Each modifies a NSManagedObject model. Many of them also present their own modal view controllers.

I need to save changes to the NSManagedObjectContext when a user either 'pops' the view controller or pushes the next view controller.

Currently, I'm hiding the default back button and setting my own UIBarButtonItem with a target of self and a custom action.

This works okay, but ideally, I want to use the default back button and run code before the pop. Is there a way I can run my own code before the pop?

(I'd prefer not to put code into viewWillDisappear as persisting to disk can be expensive and this method can also be triggered by modals being displayed by view controller.) Can it be done?

5

5 Answers

4
votes

You can do it in viewDidDisappear, after checking that self is either 1) the second last element in self.navigationController.viewControllers (the case where the next VC just got pushed) or 2) self.navigationController is nil (the self VC just got popped).

1
votes

Yes.. Navigation controller has a delegate which indicates when a view controller popped or pushed.. You can use that to do your task...

0
votes

Add following method in your code:

- (void) viewWillDisappear:(BOOL)animated{
     //your code here
}
0
votes

I use viewWillDissappear to make any changes persistant. If required i Use viewWillAppear to recoginze any changes (reload the data) that may have taken place while other puhed view controlers did their work.

0
votes

For pop check isMovingFromParent in viewWillDisappear

func viewWillDisappear(_ animation:Bool){
    super.viewWillDisappear(animation);
    if isMovingFromParent {
        // your code here
    }
}