我猜想NotificationCenter会出现EXC_BAD_ACCESS错误吗?

问题描述 投票:-1回答:1

目前我必须从AppDelegate访问ViewController的实例。但我发现这不是一个好主意,所以我决定使用

NotificationCenter.default.addObserver

代替。

这是我的代码。

*// 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)")
}

当我按下主页按钮运行应用程序并输入背景时

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

我在AppDelegate.swift中收到此错误。

我打开了僵尸对象选项,但没有控制台输出。我也试过Xcode Analyze,但问题清单上没有任何内容。

我认为对象和内存分配有问题,但我仍然无法得到我做错了什么。

ios swift exc-bad-access nsnotificationcenter
1个回答
0
投票

更改

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

@objc func applicationDidEnterBackground(_ notification : Notification) {

这是通知选择器的唯一合法签名。您的代码尝试不允许您自己编写签名。

© www.soinside.com 2019 - 2024. All rights reserved.