WKWebView代码实例化偶发崩溃求助(嵌入导航控制器时触发)
Let’s break down why you’re seeing this occasional crash and how to fix it. The core issue comes from incorrect initialization of your WKWebView, which leads to undefined internal state and the dangling pointer error you’re seeing (where a message meant for the web view gets sent to an NSString instance that reused deallocated memory).
Root Cause
Your code uses [[WKWebView new] initWithFrame:]—this is wrong in Objective-C. [WKWebView new] already creates and initializes an instance (equivalent to [[WKWebView alloc] init]). Calling initWithFrame: on an already initialized object corrupts the web view’s internal state, leading to unpredictable behavior like the crash you’re experiencing. This inconsistency only surfaces when embedded in a navigation controller because the view lifecycle timing changes, triggering the corrupted state.
Corrected Code
Here’s the fixed version of your viewDidLoad method, with key improvements:
- (void)viewDidLoad { [super viewDidLoad]; // Correct initialization: use alloc + initWithFrame directly self.webView = [[WKWebView alloc] initWithFrame:self.container.bounds]; // Disable scroll indicators self.webView.scrollView.showsVerticalScrollIndicator = NO; self.webView.scrollView.showsHorizontalScrollIndicator = NO; // Ensure web view resizes with container self.webView.autoresizingMask = (UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight); // Add web view to container [self.container addSubview:self.webView]; // Load your HTML content [self.webView loadHTMLString:@"testString" baseURL:nil]; }
Additional Tips for Reliability
For even more stable behavior, especially with dynamic layout changes (like rotation or different device sizes), use auto layout constraints instead of frame-based positioning:
- (void)viewDidLoad { [super viewDidLoad]; // Initialize with empty frame, disable autoresizing mask self.webView = [[WKWebView alloc] initWithFrame:CGRectZero]; self.webView.translatesAutoresizingMaskIntoConstraints = NO; // Disable scroll indicators self.webView.scrollView.showsVerticalScrollIndicator = NO; self.webView.scrollView.showsHorizontalScrollIndicator = NO; [self.container addSubview:self.webView]; // Pin web view to all edges of the container [NSLayoutConstraint activateConstraints:@[ self.webView.leadingAnchor.constraintEqualToAnchor:self.container.leadingAnchor, self.webView.trailingAnchor.constraintEqualToAnchor:self.container.trailingAnchor, self.webView.topAnchor.constraintEqualToAnchor:self.container.topAnchor, self.webView.bottomAnchor.constraintEqualToAnchor:self.container.bottomAnchor ]]; [self.webView loadHTMLString:@"testString" baseURL:nil]; }
This should eliminate the occasional crash when your controller is embedded in a navigation controller. The incorrect initialization was the main culprit—fixing that stabilizes the WKWebView’s internal state entirely.
内容的提问来源于stack exchange,提问作者marco garbi

