Check to see if UIViewController has already been

2019-09-07 05:58发布

I'm trying to check if a viewcontroller has already been created. If the view already exists then it should become the current view. If it doesn't exist then it should be created and made visible.

My code is

            DemoViewController *demoController = [DemoViewController alloc];
        for(DemoViewController *view in self.navigationController.viewControllers)
        {
            if([view isKindOfClass:[DemoViewController class]])
            {
                viewExists=true;
                demoController=view;
            }

        }
        if (!viewExists) {
            demoController initWithNibName:@"DemoViewController" bundle:nil;
        }
        [view release];
        [demoController release];

I'm not sure where I'm going wrong but it would appear that the for loop isn't being executed. Any help would be great!

1条回答
倾城 Initia
2楼-- · 2019-09-07 06:28

Try like this:

DemoViewController* demoController = nil;
for(int vv=0; vv<[self.navigationController.viewControllers count]; ++vv) {
    NSObject *vc = [self.navigationController.viewControllers objectAtIndex:vv];
    if([vc isKindOfClass:[DemoViewController class]]) {
        demoController = (DemoViewController*)vc;
    }
}

if (demoController == nil) {
    demoController = [[DemoViewController alloc] initWithNibName:@"DemoViewController" bundle:nil];
    // Do we need to push it into navigation controller?
}

[demoController release];
查看更多
登录 后发表回答