【问题标题】:App crashing when adding completion to the observer向观察者添加完成时应用程序崩溃
【发布时间】:2020-06-23 12:51:54
【问题描述】:

我正在尝试向通知观察者添加一个块,但在移动前景和背景时应用程序崩溃了。如果我向观察者添加方法,它的工作正常,只有在阻止它崩溃的情况下。这是我正在尝试的代码。

class ViewController: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()
        
        NotificationCenter.default.addObserver(self, selector: #selector(foregroundEntered(closure:)), name: UIApplication.willEnterForegroundNotification, object: nil)
        // Do any additional setup after loading the view.
    }

    
    @objc func foregroundEntered(closure: () -> Void) {
        /// do some stuff
    }
        
    override func viewDidDisappear(_ animated: Bool) {
        super.viewDidDisappear(animated)
        NotificationCenter.default.removeObserver(self, name: UIApplication.willEnterForegroundNotification, object: nil)
    }
}

提前致谢。

【问题讨论】:

  • 请发布崩溃日志
  • 线程 1:EXC_BAD_ACCESS (code=1, address=0x8) 我了解一些内存问题。但无法弄清楚。线程 1 队列:com.apple.main-thread(串行)
  • 试试@objc func foregroundEntered(closure: NSNotification) { ??
  • @Sh_Khan 谢谢你的帮助。这会起作用,但我需要添加一个块。我在多个地方调用相同的方法。所以我需要在那里添加一个块而不是方法。我只是在尝试阻止。
  • 选择器无法与块一起使用,您需要使用该观察者的完成回调品种

标签: swift swift3 swift4


【解决方案1】:

替换

@objc func foregroundEntered(closure: () -> Void) { 

@objc func foregroundEntered(_ notif: NSNotification) {

然后改变

NotificationCenter.default.addObserver(self, selector: #selector(foregroundEntered), name: UIApplication.willEnterForegroundNotification, object: nil)

【讨论】:

    猜你喜欢
    • 2017-04-01
    • 1970-01-01
    • 1970-01-01
    • 2020-07-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-01-10
    相关资源
    最近更新 更多