检查是否存在viewcontroller,如果不存在alloc / init(iOS)

时间:2011-01-28 17:19:51

标签: iphone

我对我经常做的事情有疑问。在创建一个新的viewcontroller之前,我检查以我想以某种方式呈现的viewcontroller命名的实例变量。

if (self.viewcontroller == nil) {
   //alloc and init the viewcontroller, then set the reference to this.
}

//Else I use the instance variable reference without making a new object of it. 

我在诸如带有单个webview的viewcontroller之类的对象上执行此操作。 webview可能打开的URL会有所不同,但这是在viewWillAppear方法中设置的。

这是不好的做法吗?我还保留了“详细”的viewcontroller。

提前致谢。

1 个答案:

答案 0 :(得分:2)

在这种情况下,我通常会像这样编写getter方法:

- (UIViewController*) viewController
    {
 if (!viewController)
        {
        viewController = [[UIViewController alloc] init];
    // ... any other setup that needs doing at this point.
        }
    return viewController;
    }

这允许我在整个代码中使用[self viewController],而不是在整个代码中检查,分配,初始化,保留。

这就是你问的问题吗?

相关问题