1
- (void)viewWillDisappear:(BOOL)animated
{
    if ([self.navigationController.viewControllers indexOfObject:self] == NSNotFound) {
        if ([self.navigationController.viewControllers.lastObject isKindOfClass:[CustomViewController class]]) {
            NSArray *tempArr = self.navigationController.viewControllers;
            self.navigationController.viewControllers = tempArr;
            [self.navigationController popViewControllerAnimated:YES];
            return;
        }
    }
    [super viewWillDisappear:animated];
}

if an user press back button and previous UIViewController is CustomViewController then pop 2 last UIViewControllers else pop 1 last UIVIewController.

I think these strings mean nothing:

        NSArray *tempArr = self.navigationController.viewControllers;
        self.navigationController.viewControllers = tempArr;

But if I delete them then I pop 2 last UIViewControllers and get the title of CustomViewController instead of the title from the current UIViewController.

Is it a bug? And will this code work in iOS 6?

Gargo
  • 704
  • 6
  • 16

2 Answers2

2

I am not sure if this will actually work, since I don't know if popViewController is checking the array before or after it pops. The idea is to remove the last object instead of popping viewController twice.

- (void)viewWillDisappear:(BOOL)animated
{
    if ([self.navigationController.viewControllers indexOfObject:self] == NSNotFound) {
        if ([self.navigationController.viewControllers.lastObject isKindOfClass:[CustomViewController class]]) {
            NSMutableArray *tempArr = [self.navigationController.viewControllers mutableCopy];
            [tempArr removeLastObject];
            self.navigationController.viewControllers = tempArr;
            return;
        }
    }
    [super viewWillDisappear:animated];
Martol1ni
  • 4,684
  • 2
  • 29
  • 39
1

There is a much better way of doing this by using unwind segues.

Essentially you set a marker point on a ViewController and then go about pushing view controllers on top of it.

Then at any point (when the user presses a button or something) you can pop back to the viewController with the marker on it.

You no longer have to work out how many view controllers to pop etc... it just works.

See this StackOverflow answer.

Community
  • 1
  • 1
Fogmeister
  • 76,236
  • 42
  • 207
  • 306