检查是否已创建UIViewController

时间:2012-09-16 23:43:35

标签: objective-c uiviewcontroller uinavigationcontroller

我正在尝试检查是否已创建了一个viewcontroller。如果视图已经存在,那么它应该成为当前视图。如果它不存在则应该创建它并使其可见。

我的代码是

            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];

我不确定我哪里出错但看起来for循环没有被执行。 任何帮助都会很棒!

1 个答案:

答案 0 :(得分:0)

试试这样:

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];