【问题标题】:NotificationCenter Crash in Swift 3Swift 3 中的 NotificationCenter 崩溃
【发布时间】:2019-05-31 02:36:58
【问题描述】:

只是我,还是 NotificationCenter 在 Swift 3 中变得一团糟? :)

我有以下设置:

// Yonder.swift
extension Notification.Name {
  static let preferenceNotification = Notification.Name("preferencesChanged")
}

// I fire the notification elsewhere, like this:
NotificationCenter.default.post(name: .preferenceNotification, object: nil)

在我的第一个视图控制器中,这很好用:

// View Controller A <-- Success!
NotificationCenter.default.addObserver(self, selector: #selector(refreshData), name: .preferenceNotification, object: nil)

func refreshData() {
  // ...
}

但是这个视图控制器:

//View Controller B <-- Crash :(
NotificationCenter.default.addObserver(self, selector: #selector(loadEntries(search:)), name: .preferenceNotification, object: nil)

func loadEntries(search:String?) {
  // ...
}

...崩溃:

[NSConcreteNotification 长度]:无法识别的选择器发送到实例

据我所知,我的观察者设置正确。知道我做错了什么吗?

【问题讨论】:

标签: ios swift3 nsnotificationcenter nsnotifications notificationcenter


【解决方案1】:

您的问题在于您的 loadEntries(search:) 方法。这不是一个有效的签名。与通知中心一起使用的选择器必须没有参数或只有一个参数。如果您有一个参数,则该参数将是Notification 对象,而不是通知名称。

您的loadEntries 必须是:

func loadEntries(_ notification: NSNotification) {
    // Optional check of the name
    if notification.name == .preferenceNotification {
    }
}

选择器需要是:

#selector(loadEntries(_:)) // or #selector(loadEntries)

【讨论】:

  • 啊,我明白了。谢谢!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-02-26
  • 2017-02-15
  • 1970-01-01
  • 2016-11-07
相关资源
最近更新 更多