如何确保iOS项目中故事板的名称串是正确的?

问题描述 投票:0回答:1

在iOS项目中。

我总是用UIStroyboard创建一个UIViewController,方法是这样的: swift:

       let sb = UIStoryboard(name: "XXXlectViewController", bundle: Bundle.main)

objective -c

       UIStoryboard *sb = [UIStoryboard storyboardWithName:@"XXXlectViewController" bundle:[NSBundle mainBundle]];

然后我在故事板上访问一个UIViewController表单。

如果别人不小心改了名字串。这个项目将无法按照预期工作。

有时候,我无法确定自己输入的字符串是否正确。

如你所知,如果我用纯代码创建一个UIViewContrller。

let xxxVC = xxxVC()

XXXVC *vc = [[XXXVC alloc] init];

当我Command BR时,我会得到错误提示。这可以帮助我们发现错误。

如何确保iOS项目中storyboard的名称串是正确的?如何减少这种使用storyboard创建UIViewControll实例的方式的危险?用Unit文本检查UIStoryboard创建的UIViewController吗?怎样才能做到呢?

ios objective-c swift uistoryboard
1个回答
-1
投票

对于Objective-C来说,你可以将你的故事板名称声明为常量,并在你的代码中使用它们。

在你的 .h 档案

FOUNDATION_EXPORT NSString *const MainStoryboaardIdentifier;

在你的 .m 档案

NSString *const MainStoryboaardIdentifier = @"Main";

而对于swift来说,最简单的可以是为它们定义一个枚举。

enum StoryboardIdentifier: String {
    case Login = "Login"
    case Main = "Main"
    case Options = "Options"
}

然后用 .Main.Login.

这样一来,自动完成也会发挥作用,可以避免打错字。此外,单元测试也应该更容易。使用一个特定的标识符在 UIStoryboard 初始化器应该导致各自的viewController。

© www.soinside.com 2019 - 2024. All rights reserved.