简体   繁体   English

Swift 3中的NotificationCenter崩溃

[英]NotificationCenter Crash in Swift 3

Is it just me, or did NotificationCenter become a hot mess in Swift 3? 它只是我,还是NotificationCenter成为Swift 3中的热点? :) :)

I have the following setup: 我有以下设置:

// 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)

In my first view controller, this works great: 在我的第一个视图控制器中,这很好用:

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

func refreshData() {
  // ...
}

But this view controller: 但是这个视图控制器:

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

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

...crashes with: ...崩溃:

[NSConcreteNotification length]: unrecognized selector sent to instance [NSConcreteNotification length]:发送到实例的无法识别的选择器

As far as I can tell, my observer is set up correctly. 据我所知,我的观察者设置正确。 Any idea what I'm doing wrong? 知道我做错了什么吗?

Your issue is with your loadEntries(search:) method. 您的问题是您的loadEntries(search:)方法。 It's not a valid signature. 这不是有效的签名。 The selector used with Notification Center must either have no parameters or just one parameter. 与Notification Center一起使用的选择器必须没有参数或只有一个参数。 And if you have one parameter, that parameter will be the Notification object, not the notification name. 如果您有一个参数,那么该参数将是Notification对象,而不是通知名称。

Your loadEntries needs to be: 你的loadEntries需要是:

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

And the selector would need to be: 选择器需要是:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM