Getting “Thread 1:EXC_BAD_ACCESS” error?

2019-05-26 22:12发布

问题:

I am creating a simple web viewer using WKWebView and the Swift language. Here is my code.

import Cocoa
import WebKit

@NSApplicationMain class AppDelegate: NSObject, NSApplicationDelegate {

    @IBOutlet var containerView : NSView! = nil
    @IBOutlet weak var window: NSWindow!


    func applicationDidFinishLaunching(aNotification: NSNotification) {
        // Insert code here to initialize your application
        var webView: WKWebView

        webView = WKWebView() //Thread 1:EXC_BAD_ACCESS (code=1,address=0x20)
        var url = NSURL(string:"http://www.google.com/")
        var req = NSURLRequest(URL: url!)
        webView.loadRequest(req)
    }

    func applicationWillTerminate(aNotification: NSNotification) {
        // Insert code here to tear down your application
    }

}

I'm now getting a "Thread 1:EXC_BAD_ACCESS" error on the webView = WKWebView() line when I try to run the application. How can I fix this?

回答1:

If that's it's all your code, than I'd say you're missing to instantiate the WKWebView. Put a breakpoint on the self.webView!.loadRequest(req) line and check whether it's nil or not.

I've never worked with WKWebView, but I think that you need a view controller. Maybe this blog post can help you: Getting started with WKWebView using Swift in iOS 8



回答2:

You forgot to initialise your WKWebView

var webView = WKWebView(frame: CGRectMake(0, 0, 320, 480))
var url = NSURL(string:"http://www.google.com/")
var req = NSURLRequest(URL: url)
webView.loadRequest(req)


回答3:

I get this error whenever I try to use a brand new minimal class as a delegate. For example:

class MyDelegate: NSObject, UIWebViewDelegate { /* ... */ }

This does not happen when I try to use the default ViewController as a delegate. For example:

class ViewController: UIViewController, UIWebViewDelegate { /* ... */ }

I would suggest using the ViewController as a delegate until we get to the bottom of this.