0

在从 swift3 到 swift4 的转换过程中,转换器已更改NotificationCenter为以下视图:

 NotificationCenter.default.addObserver(self, selector: #selector(myController.myFunction(_:)), name: NSNotification.Name.NSTextView.didChangeSelectionNotification, object: myNSTextView)

所以,因为selector.addObserver()myFunction 现在前面有 @objc 。现在编译器抱怨说该类型NSNotification.Name没有 member NSTextView。这是转换器制造的,而不是我。我很困惑。

如何解决这个问题?

更新。我在这里找到了信息如何将 NSWorkspace 通知迁移到 Swift 4?

所以我必须使用

NotificationCenter.default.addObserver(self, selector: #selector(myController.myFunction(_:)), name: NSTextView.didChangeSelectionNotification, object: myNSTextView)  
4

2 回答 2

1

正如 Gary 的评论中提到的,您需要从调用 切换过来Selector,而是使用回调。以下示例显示了为此需要进行的设置。

var didBecomeActive: (Notification) -> Void = { notification in
    print("app became active")
}

private func setupNotification() {
    NotificationCenter.default.addObserver(forName: .UIApplicationDidBecomeActive,
                                           object: nil,
                                           queue: OperationQueue.main,
                                           using: didBecomeActive)
}

首先,我创建了 var didBecomeActive,并使其成为(Notification) -> Void符合函数期望的类型。在我的示例中,我将notification值留在了回调中,但如果你不使用它,你可以用 a 替换它,_它会正常工作。

接下来,不要调用您使用的函数:

NotificationCenter.default.addObserver(self, selector: #selector(myController.myFunction(_:)), name: NSTextView.didChangeSelectionNotification, object: myNSTextView)  

我改为调用以下命令:

NotificationCenter.default.addObserver(forName: <#T##NSNotification.Name?#>, 
    object: <#T##Any?#>, 
    queue: <#T##OperationQueue?#>, 
    using: <#T##(Notification) -> Void#>)

对于using参数,只需提供您设置用于接收回调的变量,在本例中为didBecomeActive.

于 2017-09-17T04:27:08.963 回答
0

您也可以在方法之前输入@objc,它会起作用

于 2017-11-16T23:11:44.587 回答