Search code examples
iosswiftexc-bad-accessnsnotificationcenter

EXC_BAD_ACCESS error occurs with NotificationCenter I guess?


Currently I have to access instance of ViewController from AppDelegate. But I've found that's not a good idea, so I decided to use

NotificationCenter.default.addObserver

instead.

Here is my code.

*// ViewController*

override func viewDidLoad() {
    super.viewDidLoad()

    // Do some initial UI settings

    NotificationCenter.default.addObserver(self, selector: 
    #selector(applicationDidEnterBackground), name: UIApplication.didEnterBackgroundNotification, object: nil)

}

deinit {
    NotificationCenter.default.removeObserver(self)
}

// Check which object called this method
@objc func applicationDidEnterBackground(file: String = #file, line: Int = #line, function: String = #function) {
    // Do something I want to do... 
    print("applicationDidEnterBackground triggered by: \(file):\(line) : \(function)")
}

When I run the app and enter background as I press home button

Thread 1: EXC_BAD_ACCESS (code=1, address=0x1)

I get this error in AppDelegate.swift.

I turned on zombie objects option but there was no console output. I also tried Xcode Analyze but there was nothing on issue list.

I think there is something wrong about object and memory allocation, but still I can't get what exactly am I doing wrong.


Solution

  • Change

    @objc func applicationDidEnterBackground(file: String = #file, line: Int = #line, function: String = #function) {
    

    To

    @objc func applicationDidEnterBackground(_ notification : Notification) {
    

    That is the only legal signature for a notification selector. You are not permitted to make up your own signature, as your code attempts to do.