9

I have the following in a view controller (where webView is an instance variable of type UIWebView):

- (void)loadView
{
    webView = [[UIWebView alloc]initWithFrame:self.view.frame];
    [self.view addSubview:webView];
}

The first line, allocating the web view, causes a crash -- I get EXC_BAD_ACCESS and a message in the console:

Warning: Unable to restore previously selected frame

I don't understand whats causing the crash; self.view.frame is definitely a CGRect.

jscs
  • 63,694
  • 13
  • 151
  • 195
Tom
  • 269
  • 4
  • 14
  • 2
    You'd better always provide the crash log. It's hard to say w/o it. – Anton Aug 20 '11 at 20:28
  • The console says "warning: Unable to restore previously selected frame." and the line of code that allocated the UIWebView is highlighted in green and says "EXC_BAD_ACCESS". – Tom Aug 20 '11 at 20:40

4 Answers4

7

You can't use self.view accessor inside loadView, you can only use the setter. The reason is that the view accessor method in a UIViewController loads the view (if it isn't already loaded) and since you are already in loadView (loading the view) it will cause an infinite recursive loop.

If you follow the pattern for loadView from this answer you would want to do it like this instead:

webView = [[UIWebView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]];
self.view = webView;
[webView release];   // don't forget to release
Community
  • 1
  • 1
progrmr
  • 75,956
  • 16
  • 112
  • 147
6

Since you're using the loadView method you have to manually create your own view hierarchy. Since UIWebView is a subclass of UIView you could just write your loadView method like this:

webView = [[UIWebView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]];
self.view = webView;
[webView release];

Or you could skip using loadView and just place it in the viewDidLoad method like this:

webView = [[UIWebView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]];
[self.view addSubview:webView];
[webView release];

To further elaborate on why your application is crashing, when a UIViewController is instantiated its view is not created right way. This is called lazy loading, so you are trying to access a value that doesn't exist yet.

ms83
  • 1,804
  • 16
  • 13
1

You are trying to access view's frame without even creating the view. You can create a view and assign it as self.view or you can simply call [super loadView]. Try the below code.

- (void)loadView {

    [super loadView];
    webView = [[UIWebView alloc] initWithFrame:self.view.frame];
    [self.view addSubview:webView];
}
EmptyStack
  • 51,274
  • 23
  • 147
  • 178
0

I think the self.view.frame does not exist when loadView is called. You may put that code in viewDidLoad, where the self.view is loaded and frame known.

Zhao Xiang
  • 1,625
  • 2
  • 23
  • 40