开发者

Checking if a viewcontroller exist, if not alloc/init (iOS)

I have a question about something I do often. Before making a new viewcontroller I check the instance variable named after the viewcontroller I want to present in some way.

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. 

I do this on objects such as a viewcontroller with a single webview. The url the webview may open will be different, but 开发者_如何学Cthis is set in the viewWillAppear method.

Is this bad practice? I also retains the "detailed" viewcontroller.

Thanks in advance.


In cases like this, I usually write the getter method like this:

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

This allow me to use [self viewController] throughout my code, rather than check, alloc, init, retain throughout my code.

Is that what you were asking?

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜