1

I have to deal with some code I do not quite understand, similar to this:

In PrimaryViewController:

- (void)setup
{
    secondViewController = [[SecondViewController alloc] initWithNibName:nil bundle:nil];
    [secondViewController loadViewWithFrame:viewFrame webViewURL:url];
    [self.view addSubview:secondViewController.view];
    ...
}

And in SecondViewController:

- (void)loadViewWithFrame:(CGRect)frame webViewURL:(NSString *)url
{
    if (![self isViewLoaded]) {
        [self loadView];
    }
    self.view = [[UIView alloc] initWithFrame:frame];
    UIWebView *webView = [[UIWebView alloc] initWithFrame:CGRectMake(0, 0, frame.size.width, frame.size.height)];
    [webView loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:url]]];
    [self.view addSubview:webView];
    ...
}
  1. Do you think it is legitimate to call [self loadView]? (Apple normally don't want you to)
  2. What is the point to recreate self.view right after?

Note: project minimum SDK is iOS7.

4
  • 2
    -loadView is called whenever you access the view property and it hasn't been initialized yet. The if block at the beginning of -loadViewWithFrame is redundant. Feb 4, 2016 at 2:50
  • 1
    The guy you inherited that code from didn't read Apple's docs and has probably some serious misconceptions about view life cycle. Feb 4, 2016 at 2:51
  • 1
    This code also makes no sense. The job of loadView is to set self.view. But after doing that, the next line of code throws away the view that was just loaded.
    – Rob Napier
    Feb 4, 2016 at 13:09
  • I guess I will then remove [self loadView];. I wonder if self.view = affects the lifecycle of the viewController and calls to viewWillAppear: and such.
    – Cœur
    Feb 5, 2016 at 0:24

1 Answer 1

0

Call [self loadView] is not legitimate in the given example.

Recreating self.view is not legitimate in the given example: it makes initWithNibName:bundle: useless.

So both statements can be removed.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.