Sandeep Bansal
Sandeep Bansal

Reputation: 6394

Check if controller has already been loaded XCode

I have the following code to push a new ViewController in a Split View Controller:

Level4ViewController *controller = [[Level4ViewController alloc] initWithNibName:@"ModuleViewController" bundle:nil];
    [[detailViewController navigationController] pushViewController:controller animated:YES];
    [controller release], controller = nil;

The only problem I have, if I were to run this again, a new controller will show, I would like to be able to go to the view that I had before with all my data.

Can anyone help me out here.

Thanks.

EDIT:

Updated code?

Level4ViewController *controller;
    for(UIView *view in self.navigationController.viewControllers)
    {
        if([view isKindOfClass:[Level4ViewController class]])
        {
            controller = view;
            if(controller == nil)
            {
                controller = [[Level4ViewController alloc] initWithNibName:@"ModuleViewController" bundle:nil];
            }
            else {
                controller = [self.navigationController.viewControllers objectAtIndex:1];
            }

        }
    }

    [[detailViewController navigationController] pushViewController:controller animated:YES];
    [controller release], controller = nil;

Upvotes: 1

Views: 3961

Answers (2)

Mazen K
Mazen K

Reputation: 3662

If you are using a navigation controller

FirstScreenViewController *firstScreenVC = [self.storyboard instantiateViewControllerWithIdentifier:@"1S"];

    if (![self.navigationController.topViewController isKindOfClass:FirstScreenViewController.class])
        [self.navigationController pushViewController:firstScreenVC animated:YES];

Upvotes: 0

saadnib
saadnib

Reputation: 11145

UINavigationController has a property viewControllers which is a NSArray that hold all the stack that has been pushed to the navigation controller, in this array you can check for your view controller if it is there use that one - you check like this -

Level4ViewController *lvc;

for(UIView *view in self.navigationController.viewControllers)
{
     if([view isKindOfClass:[Level4ViewController class]])
     {
          lvc = view;
     }
}

and if you already knows that at which index your viewcontroller is there then you can get it from that index as -

Level4ViewController *lvc = [self.navigationController.viewControllers objectAtIndex:1];

update -

Level4ViewController *controller;
for(UIView *view in self.navigationController.viewControllers)
{
     if([view isKindOfClass:[Level4ViewController class]])
     {
         controller = view;
     }
}

if(controller == nil)
{
    controller = [[Level4ViewController alloc] initWithNibName:@"ModuleViewController" bundle:nil];
}

[[detailViewController navigationController] pushViewController:controller animated:YES];
[controller release], controller = nil;

Upvotes: 1

Related Questions