如何使这个UINavigationController寻求代码更优雅?

时间:2013-10-15 09:08:25

标签: ios objective-c xcode5

-(UINavigationController *) navigationControllerOfParentOrSelf //These 2 functions are short so I just go ahead
{
    UIViewController * current=self;
    while (current) {
        UINavigationController * nav = current.navigationController;
        if (nav) {
            return nav;
        }
        current=current.parentViewController;
    }
    return nil;
}

-(UITabBarController *) tabBarControllerOfParentOrSelf
{
    UIViewController * current=self;
    while (current) {
        UITabBarController * tc = current.tabBarController;
        if (tc) {
            return tc;
        }
        current=current.parentViewController;
    }
    return nil;
}

在那里看起来很多重复的代码。

基本上我只是想知道UIViewController是否在UINavigationController中。当UIViewController是childViewController

时,navController属性通常是nil

2 个答案:

答案 0 :(得分:2)

我会建议这样的事情:

-(UINavigationController *) navigationControllerOfParentOrSelf
{
    return [self parrentControllerOfParrentOrSelfWithGetter: @selector(navigationController)];
}

-(UITabBarController *) tabBarControllerOfParentOrSelf
{
    return [self parrentControllerOfParrentOrSelfWithGetter: @selector(tabBarController)];

}

- (id) parrentControllerOfParrentOrSelfWithGetter: (SEL) getter
{
    UIViewController * current=self;
    while (current) {
        id res = [current performSelector: getter];
        if (res) {
            return tc;
        }
        current=current.parentViewController;
    }
    return nil;
}

答案 1 :(得分:1)

你可以这样做:

-(id) getViewController:(BOOL)isNavController
{
     id controller = nil;
     if(isNavController)
     {
        controller  = self.navigationController;
     }
     else
     {
         controller  = self.tabBarController;
     }

     return controller;
}