【问题标题】:How to make this UINavigationController seeking code more elegant?如何让这个 UINavigationController 寻求代码更优雅?
【发布时间】:2013-10-15 09:08:25
【问题描述】:
-(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 时,navigationController 属性通常为 nil

【问题讨论】:

  • 你的循环没有意义。如果navigationController 属性不为零,它将执行一次。如果它为 nil,它将永远运行。
  • 已修复。好的,这不是问题。

标签: ios objective-c xcode5


【解决方案1】:

我会建议这样的事情:

-(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;
}

【讨论】:

  • 不错的答案,比我的好:)
【解决方案2】:

你可以这样做:

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

     return controller;
}

【讨论】:

  • 这是一个改进。问题是我们使用了一个布尔变量。如果我们稍后想添加更多属性怎么办。我正在考虑 performSelector(@navigationController)