memory bad access?

2019-08-22 02:01发布

问题:

How can this statement ever give me bad access?

myWebView = [[NewsWebViewController alloc] initWithNibName:@"NewsWebViewController" bundle:nil];
[[self.view.superview superview] addSubview:myWebView.view];

 if(myWebView!=nil) {
    [myWebView release];
    myWebView = nil;
}

Ive ran it through instruments and it crashes every time. myWebView is an ivar in my header file.

Any thoughts? Many thanks

Jules

回答1:

ok here is the actual issue. When I removed the webview it gets dealloc'd but I didnt set its delegate to nil. Therefore webViewDidFinishLoading etc was trying to access it and giving me bad access.

Thanks to all for your input.



回答2:

You should check that myWebView is nil before you add it's view to a subview. You do not need to set myWebView to nil after you release it.



回答3:

You are setting mywebview to nil after releasing so it crashes as the object no longer exists. Do it in this order:

if(myWebView!=nil) {

  myWebView = nil;
  [myWebView release];

}