ios - Swift 3 中的通知中心崩溃

标签 ios swift3 nsnotificationcenter nsnotifications notificationcenter

这只是我的问题,还是 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 中,这很好用:

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

func refreshData() {
  // ...
}

但是这个 View Controller :

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

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

...崩溃:

[NSConcreteNotification length]: unrecognized selector sent to instance

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

最佳答案

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

您的loadEntries 需要:

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

选择器需要是:

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

关于ios - Swift 3 中的通知中心崩溃,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40644703/

相关文章:

ios - swift3 中的选择器

ios - 当导航 Controller 推/拉 UIViewController 时,如何添加和删除通知观察器?

ios - NSDate dateWithTimeIntervalSince1970 不返回 GMT/UTC 时间

iphone - 为什么即使我覆盖 touchesMoved :withEvent:? UIScrollView 的子类仍然滚动

objective-c - uint16_t 与 UInt16

ios - 在 for 循环中处理 UI 更新 - iOS

iOS、Swift、Objective C、UserNotificationCenter、NSNotificationCenter

ios - 我可以在不使用 "undocumented api"的情况下为 UnknownPersonViewController 创建自定义 Nib 吗?

swift - 在 UIView.Animate 中执行 2 CGAffineTransform - Swift

swift - Cocoa/Swift 3.0 替换 NSNumberFormatter.isPartialStringValid